﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Collections;
using System.Windows.Forms;
using System.IO;

namespace Administrator
{
    public class cDbOracle
    {
        private static fSplash SplashForm = null;
        private static fProgress ProgressForm = null;
        public struct DB_ACCESS
        {
            public String Provider;
            public String Server;
            public String Instance;                                   
            public String Scheme;
            public String Source;
            public String UserName;
            public String Password;
            public Boolean SaveIdentification;
        }
        
        public static DB_ACCESS DbAccess = new DB_ACCESS();
        public static OleDbConnection DbConnect;
        public const String Oracle9i = "Oracle 9i";
        public const String Oracle10g = "Oracle 10g";
        public const String Oracle11g = "Oracle 11g";
        private static Form m_parent;
        public const String DriverPath = @"C:\Program Files\ASKUE\KTSConceptShell\";

        public static  void SetParent(Form parent)
        {
            m_parent = parent;
        }

        private static void AddToLoading(String ActionDesc, Int32 Count)
        {
            if (SplashForm != null)
            {
                SplashForm.lbProgress.Text = ActionDesc;
                if (SplashForm.pbProgress.Value + Count < SplashForm.pbProgress.Maximum)
                {
                    SplashForm.pbProgress.Value += Count;
                    Application.DoEvents();
                }
                    
            }
            if (ProgressForm != null)
            {
                ProgressForm.lbProgress.Text = ActionDesc;
                if (ProgressForm.pbProgress.Value + Count < ProgressForm.pbProgress.Maximum)
                    ProgressForm.pbProgress.Value += Count;
                Application.DoEvents();
            }
        }
        private static void AddToProgress(Int32 Count)
        {
            if (ProgressForm != null)
            {
                if (ProgressForm.pbProgress.Value + Count < ProgressForm.pbProgress.Maximum)
                    ProgressForm.pbProgress.Value += Count;
                Application.DoEvents();
            }
        }

        public static Boolean OpenConnection()
        {
            Boolean Result = false;
            String ConnectStr = "";

            try
            {
                if (DbAccess.Provider.Trim() != "") ConnectStr += DbAccess.Provider.Trim() + ";";
                if (DbAccess.Server.Trim() != "")
                {
                    if (DbAccess.Source == Oracle9i) ConnectStr += "Server=" + DbAccess.Server.Trim() + ";";
                    else ConnectStr += "Data Source=" + DbAccess.Server.Trim() + ";";                                
                }
                if (DbAccess.UserName.Trim() != "") ConnectStr += "User ID=" + DbAccess.UserName.Trim() + ";";
                if (DbAccess.Password.Trim() != "") ConnectStr += "password=" + DbAccess.Password.Trim() + ";";
                if (DbAccess.Instance.Trim() != "")
                {
                    if (DbAccess.Source == Oracle9i) ConnectStr += "Data Source=" + DbAccess.Instance.Trim() + ";";
                    else ConnectStr += "database=" + DbAccess.Instance.Trim() + ";";                
                }
                DbConnect = new OleDbConnection(ConnectStr);
                DbConnect.Open();

                if (DbAccess.Scheme.Trim() != "")
                {
                    try
                    {
                        OleDbCommand DbCommand = DbConnect.CreateCommand();
                        DbCommand.CommandText = "alter session set current_schema =" + DbAccess.Scheme;
                        DbCommand.ExecuteNonQuery();
                    }
                    catch (Exception ee)
                    {
                        MessageBox.Show(ee.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    

                }
                Result = true;                
            }
            catch (Exception ee)
            {   
                if (DbConnect != null) DbConnect.Close();      
                DbConnect = null;                
                MessageBox.Show("Ошибка доступа к БД:" + "\u000D\u000A" + ee.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                //InfoAboutWindowsLibrary.sInfoWinWork.sStop("Источник данных \"" + Obj.Name + "\" загружен");
            }           
            return Result;
        }

        //Загрузка списка подключенных к БД программ
        public static Boolean CheckProgrammDBConnection(String ProgName)
        {
            OleDbCommand DbCommand;
            OleDbDataAdapter DbDataAdapter;
            DataSet DbDataSet;
            Boolean Result = false;
            String ProgStr = "";

            try
            {
                //Загрузка списка типов тарифов для справочника
                DbCommand = DbConnect.CreateCommand();
                DbDataAdapter = new OleDbDataAdapter(DbCommand);
                DbDataSet = new DataSet();
                DbCommand.CommandText = "select distinct PROGRAM from V$SESSION where USERNAME is not null";
                DbDataAdapter.Fill(DbDataSet, "vsession");
                foreach (DataRow DbDataRow in DbDataSet.Tables["vsession"].Rows)
                {
                    if (DbDataRow["PROGRAM"] != null && DbDataRow["PROGRAM"].GetType() != typeof(DBNull))
                        ProgStr = DbDataRow["PROGRAM"].ToString();
                    if (ProgStr == ProgName)
                    {
                        Result = true;
                        break;
                    }
                }
            }
            catch (Exception)
            {
                //MessageBox.Show(e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);                
            }
            return Result;
        }
        
        
        /// <summary>
        /// Загрузка струтуры дерева сети из БД
        /// </summary>
        /// <param name="FirstTime"></param>
        /// <returns></returns>
        public static Boolean LoadNetwork(Boolean FirstTime)
        {
            Boolean Result = true;
            Int32 i, j, k;

            if (cMain.MainWindow != null)
            {
                for (i = 0; i < cMain.MainWindow.Controls.Count; i++)
                    cMain.MainWindow.Controls[i].Enabled = false;
                if (FirstTime)
                {
                    SplashForm = new fSplash();
                    SplashForm.InProgress = true;
                    SplashForm.pbProgress.Maximum = 15;
                    SplashForm.pbProgress.Value = 0;
                    SplashForm.Show(cMain.MainWindow);
                }
                else
                {
                    ProgressForm = new fProgress();
                    ProgressForm.Text = "Загрузка...";
                    ProgressForm.InProgress = true;
                    ProgressForm.pbProgress.Maximum = 15;
                    ProgressForm.pbProgress.Value = 0;
                    ProgressForm.Show(cMain.MainWindow);   
                }
            }

            //Заполнение по умолчанию параметров сети        
            cMain.ResetNetwork();
            cGroup.ResetNetwork();
            //Загрузка справочника типов устройств для справочника
            AddToLoading("Загрузка справочника типов устройств...", 0);
            Result = LoadDeviceTypeList();

            //Загрузка справочника типов счетчиков
            AddToLoading("Загрузка справочника типов счетчиков...", 1);
            if (Result) 
                Result = LoadMeterList();

            //Загрузка справочника каналов связи
            AddToLoading("Загрузка справочника каналов связи...", 1);
            if (Result) 
                Result = LoadCommChanList();

            //Загрузка справочника тарифов
            AddToLoading("Загрузка справочника тарифов...", 1);
            if (Result) 
                Result = LoadTariffList();

            //Загрузка справочника пользователей
            AddToLoading("Загрузка справочника пользователей...", 1);
            if (Result) 
                Result = LoadUserList();

            //Загрузка территориальных объединений
            AddToLoading("Загрузка списка территориальных объединений...", 1);
            if (Result) 
                Result = LoadDC();

            //Загрузка объектов учета
            AddToLoading("Загрузка списка объектов учета...", 1);
            if (Result) 
                Result = LoadObjects();
            
            //Загрузка расписания сбора объектов учета
            AddToLoading("Загрузка расписаний сбора объектов учета...", 1);
            for (i = 0; (i < cMain.Objects.Length) && (Result); i++) 
                Result = LoadObjectSchedule(i);

            //Загрузка устройств объектов учета
            AddToLoading("Загрузка списка устройств объектов учета...", 1);
            for (i = 0; (i < cMain.Objects.Length) && (Result); i++) 
                Result = LoadObjectDevices(i);

            //Загрузка коммутационного оборудования устройств
            AddToLoading("Загрузка коммутационного оборудования устройств...", 1);
            for (i = 0; (i < cMain.Objects.Length) && (Result); i++)
            {
                for (j = 0; (j < cMain.Objects[i].Device.Length) && (Result); j++) 
                    Result = LoadDeviceCommEqupment(i, j);
            }
            //Загрузка присоединений устройств
            AddToLoading("Загрузка списка присоединений устройств...", 1);
            for (i = 0; (i < cMain.Objects.Length) && (Result); i++)
            {
                for (j = 0; (j < cMain.Objects[i].Device.Length) && (Result); j++) 
                    Result = LoadDeviceJoins(i, j);
            }
            //Загрузка каналов учета присоединений
            AddToLoading("Загрузка списка каналов учета присоединений...", 1);
            for (i = 0; (i < cMain.Objects.Length) && (Result); i++)
            {
                for (j = 0; (j < cMain.Objects[i].Device.Length) && (Result); j++)
                {
                    for (k = 0; (k < cMain.Objects[i].Device[j].Join.Length) && (Result); k++)                            
                        Result = LoadJoinChannels(i, j, k);                            
                }                            
            }
            //Загрузка линий электропередач (потери) присоединений
            AddToLoading("Загрузка линий электропередач присоединений...", 1);
            for (i = 0; (i < cMain.Objects.Length) && (Result); i++)
            {
                for (j = 0; (j < cMain.Objects[i].Device.Length) && (Result); j++)
                {
                    for (k = 0; (k < cMain.Objects[i].Device[j].Join.Length) && (Result); k++)
                        Result = LoadJoinConnectionLines(i, j, k);
                }
            }
            //Загрузка групп отчетов присоединений
            AddToLoading("Загрузка списка групп отчетов присоединений...", 1);
            for (i = 0; (i < cMain.Objects.Length) && (Result); i++)
            {
                for (j = 0; (j < cMain.Objects[i].Device.Length) && (Result); j++)
                {
                    for (k = 0; (k < cMain.Objects[i].Device[j].Join.Length) && (Result); k++)
                        Result = LoadJoinReportGroups(i, j, k);
                }
            }

            AddToLoading("Загрузка списка обнаруженных устройств...", 1);
            for (i = 0; (i < cMain.Objects.Length) && (Result); i++)
            {
                for (j = 0; (j < cMain.Objects[i].Device.Length) && (Result); j++)
                {
                    Result = LoadFindedDevice(i, j);
                }
            }
            AddToLoading("Загрузка завершена.", 1);
            if (cMain.MainWindow != null)
            {
                for (i = 0; i < cMain.MainWindow.Controls.Count; i++)
                    cMain.MainWindow.Controls[i].Enabled = true;
                if (SplashForm != null)
                {
                    SplashForm.InProgress = false;
                    SplashForm.Close();
                    SplashForm.Dispose();
                    SplashForm = null;
                }
                if (ProgressForm != null)
                {
                    ProgressForm.InProgress = false;
                    ProgressForm.Close();
                    ProgressForm.Dispose();
                    ProgressForm = null;
                }
            }   
            return Result;
        }

        public static string GetDeviceDllNameForID(int id)
        {
            for (int i = 0; i < cMain.DevTypeList.Length; i++)
            {
                if (cMain.DevTypeList[i].ID == id)
                    return cMain.DevTypeList[i].DeviceDllName;
            }

            return string.Empty;
        }

        //Загрузка списка типов устройств для справочника
        private static Boolean LoadDeviceTypeList()
        {
            OleDbCommand DbCommand;
            OleDbDataAdapter DbDataAdapter;
            DataSet DbDataSet;
            Boolean Result = false;
            Int32 Idx;

            cMain.DevTypeList = new cMain.DEVTYPE_SETTING[0];
            if (DbConnect != null)
            {
                try
                {
                    //Загрузка типов устройств для справочника
                    DbCommand = DbConnect.CreateCommand();
                    DbDataAdapter = new OleDbDataAdapter(DbCommand);
                    DbDataSet = new DataSet();                    
                    DbCommand.CommandText = "select * from DEVREF order by DEVICENAME";
                    DbDataAdapter.Fill(DbDataSet, "DEVREF");

                    
                    foreach (DataRow DbDataRow in DbDataSet.Tables["DEVREF"].Rows)
                    {
                        if (DbDataRow["DEVICENAME"] != null && DbDataRow["DEVICENAME"].GetType() != typeof(DBNull) &&
                            DbDataRow["PROTOCOLNAME"] != null && DbDataRow["PROTOCOLNAME"].GetType() != typeof(DBNull))
                        {
                            string debugstrDEVICENAME = DbDataRow["DEVICENAME"].ToString();
                            string debugstrPROTOCOLNAME = DbDataRow["PROTOCOLNAME"].ToString();

                            if (File.Exists(DriverPath + DbDataRow["DEVICENAME"].ToString()) &&
                                File.Exists(DriverPath + DbDataRow["PROTOCOLNAME"].ToString()))
                            {

                                Idx = cMain.DevTypeList.Length;
                                Array.Resize(ref cMain.DevTypeList, Idx + 1);
                                cMain.DevTypeList[Idx].ItemAction.DBExist = true;
                                cMain.DevTypeList[Idx].ItemAction.Changed = false;
                                cMain.DevTypeList[Idx].ItemAction.Deleted = false;
                                cMain.DevTypeList[Idx].ID = -1;
                                cMain.DevTypeList[Idx].DeviceDllName = "";
                                cMain.DevTypeList[Idx].ProtocolDLLName = "";
                                cMain.DevTypeList[Idx].Caption = "";
                                cMain.DevTypeList[Idx].DeviceKind = 0;
                                cMain.DevTypeList[Idx].ChannelCount = 0;
                                cMain.DevTypeList[Idx].FileCodeNPATS = "";
                                cMain.DevTypeList[Idx].ProtocolSetting = new Byte[0];

                                if (DbDataRow["DEVID"] != null && DbDataRow["DEVID"].GetType() != typeof(DBNull))
                                    cMain.DevTypeList[Idx].ID = Convert.ToInt32(DbDataRow["DEVID"].ToString());
                                if (DbDataRow["DEVICENAME"] != null && DbDataRow["DEVICENAME"].GetType() != typeof(DBNull))
                                    cMain.DevTypeList[Idx].DeviceDllName = DbDataRow["DEVICENAME"].ToString();
                                if (DbDataRow["PROTOCOLNAME"] != null && DbDataRow["PROTOCOLNAME"].GetType() != typeof(DBNull))
                                    cMain.DevTypeList[Idx].ProtocolDLLName = DbDataRow["PROTOCOLNAME"].ToString();
                                if (DbDataRow["TITLE"] != null && DbDataRow["TITLE"].GetType() != typeof(DBNull))
                                    cMain.DevTypeList[Idx].Caption = DbDataRow["TITLE"].ToString();
                                if (DbDataRow["DEVTYPE"] != null && DbDataRow["DEVTYPE"].GetType() != typeof(DBNull))
                                    cMain.DevTypeList[Idx].DeviceKind = Convert.ToByte(DbDataRow["DEVTYPE"].ToString());
                                if (DbDataRow["CHANNELS"] != null && DbDataRow["CHANNELS"].GetType() != typeof(DBNull))
                                    cMain.DevTypeList[Idx].ChannelCount = Convert.ToInt32(DbDataRow["CHANNELS"].ToString());
                                if (DbDataRow["FILECODESNPATS"] != null && DbDataRow["FILECODESNPATS"].GetType() != typeof(DBNull))
                                    cMain.DevTypeList[Idx].FileCodeNPATS = DbDataRow["FILECODESNPATS"].ToString();
                                if (DbDataRow["SETTINGS"] != null && DbDataRow["SETTINGS"].GetType() != typeof(DBNull))
                                    cMain.DevTypeList[Idx].ProtocolSetting = (Byte[])DbDataRow["SETTINGS"];
                            }
                        }
                    }

                   

                    Result = true;
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return Result;
        }
        //Загрузка списка типов счетчиков для справочника
        private static Boolean LoadMeterList()
        {
            OleDbCommand DbCommand;
            OleDbDataAdapter DbDataAdapter;
            DataSet DbDataSet;
            Boolean Result = false;
            Int32 Idx;

            cMain.MeterList = new cMain.METER_SETTING[0];
            if (DbConnect != null)
            {
                try
                {
                    //Загрузка типов счетчиков для справочника
                    DbCommand = DbConnect.CreateCommand();
                    DbDataAdapter = new OleDbDataAdapter(DbCommand);
                    DbDataSet = new DataSet();
                    DbCommand.CommandText = "select * from METERS order by TITLE";
                    DbDataAdapter.Fill(DbDataSet, "METERS");

                    foreach (DataRow DbDataRow in DbDataSet.Tables["METERS"].Rows)
                    {
                        Idx = cMain.MeterList.Length;
                        Array.Resize(ref cMain.MeterList, Idx + 1);

                        cMain.MeterList[Idx].ItemAction.DBExist = true;
                        cMain.MeterList[Idx].ItemAction.Changed = false;
                        cMain.MeterList[Idx].ItemAction.Deleted = false;
                        cMain.MeterList[Idx].ID = -1;
                        cMain.MeterList[Idx].Caption = "";
                        cMain.MeterList[Idx].Precision = 1;
                        cMain.MeterList[Idx].BeforeComma = 6;
                        cMain.MeterList[Idx].AfterComma = 2;
                        cMain.MeterList[Idx].MeterConst = 0;
                        cMain.MeterList[Idx].Phase = 1;
                        cMain.MeterList[Idx].SelfDemand = 0;

                        if (DbDataRow["METER"] != null && DbDataRow["METER"].GetType() != typeof(DBNull))
                            cMain.MeterList[Idx].ID = Convert.ToInt32(DbDataRow["METER"].ToString());
                        if (DbDataRow["TITLE"] != null && DbDataRow["TITLE"].GetType() != typeof(DBNull))
                            cMain.MeterList[Idx].Caption = DbDataRow["TITLE"].ToString();
                        if (DbDataRow["PREC"] != null && DbDataRow["PREC"].GetType() != typeof(DBNull))
                            cMain.MeterList[Idx].Precision = Convert.ToDouble(DbDataRow["PREC"].ToString());
                        if (DbDataRow["INTDIGITS"] != null && DbDataRow["INTDIGITS"].GetType() != typeof(DBNull))
                            cMain.MeterList[Idx].BeforeComma = Convert.ToByte(DbDataRow["INTDIGITS"].ToString());
                        if (DbDataRow["DECIMALDIGITS"] != null && DbDataRow["DECIMALDIGITS"].GetType() != typeof(DBNull))
                            cMain.MeterList[Idx].AfterComma = Convert.ToByte(DbDataRow["DECIMALDIGITS"].ToString());
                        if (DbDataRow["KOEFF"] != null && DbDataRow["KOEFF"].GetType() != typeof(DBNull))
                            cMain.MeterList[Idx].MeterConst = Convert.ToInt32(DbDataRow["KOEFF"].ToString());
                        if (DbDataRow["PHASETYPE"] != null && DbDataRow["PHASETYPE"].GetType() != typeof(DBNull))
                            cMain.MeterList[Idx].Phase = Convert.ToByte(DbDataRow["PHASETYPE"].ToString());
                        if (DbDataRow["SELFUSE"] != null && DbDataRow["SELFUSE"].GetType() != typeof(DBNull))
                            cMain.MeterList[Idx].SelfDemand = Convert.ToDouble(DbDataRow["SELFUSE"].ToString());
                    }
                    Result = true;
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return Result;
        }
        //Загрузка списка каналов связи для справочника
        private static Boolean LoadCommChanList()
        {
            OleDbCommand DbCommand;
            OleDbDataAdapter DbDataAdapter;
            DataSet DbDataSet;
            Boolean Result = false;
            Int32 Idx;

            cMain.CommChanList = new cMain.COMMCHAN_SETTING[0];
            if (DbConnect != null)
            {
                try
                {
                    //Загрузка списка каналов связи для справочника
                    DbCommand = DbConnect.CreateCommand();
                    DbDataAdapter = new OleDbDataAdapter(DbCommand);
                    DbDataSet = new DataSet();           
                    DbCommand.CommandText = "select * from COMCHAN order by COMNAME";
                    DbDataAdapter.Fill(DbDataSet, "COMCHAN");

                    cGroup.Network.CommChan = new cGroup.MODULE_SETTING[DbDataSet.Tables["COMCHAN"].Rows.Count];
                    int index = 0;
                    foreach (DataRow DbDataRow in DbDataSet.Tables["COMCHAN"].Rows)
                    {
                        if (DbDataRow["COMNAME"] != null && DbDataRow["COMNAME"].GetType() != typeof(DBNull))
                            if (File.Exists(DriverPath + DbDataRow["COMNAME"].ToString()))
                            {
                                Idx = cMain.CommChanList.Length;
                                Array.Resize(ref cMain.CommChanList, Idx + 1);
                                cMain.CommChanList[Idx].ItemAction.DBExist = true;
                                cMain.CommChanList[Idx].ItemAction.Changed = false;
                                cMain.CommChanList[Idx].ItemAction.Deleted = false;
                                cMain.CommChanList[Idx].ID = -1;
                                cMain.CommChanList[Idx].DllName = "";
                                cMain.CommChanList[Idx].Caption = "";
                                cMain.CommChanList[Idx].GroupID = 1;
                                cMain.CommChanList[Idx].Setting = new Byte[0];
                                
                                if (DbDataRow["CHANID"] != null && DbDataRow["CHANID"].GetType() != typeof(DBNull))
                                    cMain.CommChanList[Idx].ID = Convert.ToInt32(DbDataRow["CHANID"].ToString());
                                if (DbDataRow["COMNAME"] != null && DbDataRow["COMNAME"].GetType() != typeof(DBNull))
                                    cMain.CommChanList[Idx].DllName = DbDataRow["COMNAME"].ToString();
                                if (DbDataRow["NAME"] != null && DbDataRow["NAME"].GetType() != typeof(DBNull))
                                    cMain.CommChanList[Idx].Caption = DbDataRow["NAME"].ToString();
                                if (DbDataRow["PORT"] != null && DbDataRow["PORT"].GetType() != typeof(DBNull))
                                    cMain.CommChanList[Idx].GroupID = Convert.ToByte(DbDataRow["PORT"].ToString());
                                if (DbDataRow["SETTING"] != null && DbDataRow["SETTING"].GetType() != typeof(DBNull))
                                    cMain.CommChanList[Idx].Setting = (Byte[])DbDataRow["SETTING"];

                                cGroup.Network.CommChan[Idx].ID = index++;// cMain.CommChanList[Idx].ID;
                                cGroup.Network.CommChan[Idx].Setting = cMain.CommChanList[Idx].Setting;
                                cGroup.Network.CommChan[Idx].Caption = cMain.CommChanList[Idx].Caption;
                                cGroup.Network.CommChan[Idx].SettingsInDB = cMain.CommChanList[Idx];
                                cGroup.Network.CommChan[Idx].TypeDescription = 
                                    cMain.CommChanList[Idx].DllName.Substring(0,cMain.CommChanList[Idx].DllName.IndexOf('.', 0));
                                

                            }
                    }  
                    Result = true;
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return Result;
        }
        //Загрузка списка типов тарифов для справочника
        private static Boolean LoadTariffList()
        {
            OleDbCommand DbCommand;
            OleDbDataAdapter DbDataAdapter;
            DataSet DbDataSet;
            Boolean Result = false;
            Int32 Idx;

            cMain.TariffList = new cMain.TARIFF_SETTING[0];
            if (DbConnect != null)
            {
                try
                {
                    //Загрузка списка типов тарифов для справочника
                    DbCommand = DbConnect.CreateCommand();
                    DbDataAdapter = new OleDbDataAdapter(DbCommand);
                    DbDataSet = new DataSet();                 
                    DbCommand.CommandText = "select * from TARIFF order by NM";
                    DbDataAdapter.Fill(DbDataSet, "TARIFF");
                    foreach (DataRow DbDataRow in DbDataSet.Tables["TARIFF"].Rows)
                    {
                        Idx = cMain.TariffList.Length;
                        Array.Resize(ref cMain.TariffList, Idx + 1);
                        cMain.TariffList[Idx].ItemAction.DBExist = true;
                        cMain.TariffList[Idx].ItemAction.Changed = false;
                        cMain.TariffList[Idx].ItemAction.Deleted = false;
                        cMain.TariffList[Idx].ID = -1;
                        cMain.TariffList[Idx].Caption = "";
                        cMain.TariffList[Idx].FillColor = 16777215;

                        if (DbDataRow["IDTF"] != null && DbDataRow["IDTF"].GetType() != typeof(DBNull))
                            cMain.TariffList[Idx].ID = Convert.ToInt32(DbDataRow["IDTF"].ToString());
                        if (DbDataRow["NM"] != null && DbDataRow["NM"].GetType() != typeof(DBNull))
                            cMain.TariffList[Idx].Caption = DbDataRow["NM"].ToString();
                        if (DbDataRow["COLOR"] != null && DbDataRow["COLOR"].GetType() != typeof(DBNull))
                            cMain.TariffList[Idx].FillColor = Convert.ToInt32(DbDataRow["COLOR"].ToString());
                    }                    
                    Result = true;
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return Result;
        }
        //Загрузка списка пользователей для справочника
        private static Boolean LoadUserList()
        {
            OleDbCommand DbCommand;
            OleDbDataAdapter DbDataAdapter;
            DataSet DbDataSet;
            Boolean Result = false;
            Int32 Idx;

            cMain.UserList = new cMain.USER_SETTING[0];
            if (DbConnect != null)
            {
                try
                {
                    //Загрузка списка пользователей для справочника
                    DbCommand = DbConnect.CreateCommand();
                    DbDataAdapter = new OleDbDataAdapter(DbCommand);
                    DbDataSet = new DataSet();
                    DbCommand.CommandText = "select * from TELECONTROL_USERS where TCURID != 0 order by TCUSER";
                    DbDataAdapter.Fill(DbDataSet, "TELECONTROL_USERS");                     
                    foreach (DataRow DbDataRow in DbDataSet.Tables["TELECONTROL_USERS"].Rows)
                    {
                        Idx = cMain.UserList.Length;
                        Array.Resize(ref cMain.UserList, Idx + 1);
                        cMain.UserList[Idx].ItemAction.DBExist = true;
                        cMain.UserList[Idx].ItemAction.Changed = false;
                        cMain.UserList[Idx].ItemAction.Deleted = false;
                        cMain.UserList[Idx].ID = -1;
                        cMain.UserList[Idx].Caption = "";
                        cMain.UserList[Idx].Password = "";
                        cMain.UserList[Idx].AccessID = -1;

                        if (DbDataRow["TCUSERID"] != null && DbDataRow["TCUSERID"].GetType() != typeof(DBNull))
                            cMain.UserList[Idx].ID = Convert.ToInt32(DbDataRow["TCUSERID"].ToString());
                        if (DbDataRow["TCUSER"] != null && DbDataRow["TCUSER"].GetType() != typeof(DBNull))
                            cMain.UserList[Idx].Caption = DbDataRow["TCUSER"].ToString();
                        if (DbDataRow["TCPASSWORD"] != null && DbDataRow["TCPASSWORD"].GetType() != typeof(DBNull))
                            cMain.UserList[Idx].Password = DbDataRow["TCPASSWORD"].ToString();
                        if (DbDataRow["TCURID"] != null && DbDataRow["TCURID"].GetType() != typeof(DBNull))
                            cMain.UserList[Idx].AccessID = Convert.ToInt32(DbDataRow["TCURID"].ToString());
                    }

                    cMain.AccessList = new cMain.ACCESS_SETTING[0];
                    DbCommand.CommandText = "select * from TELECONTROL_USERS_REF where TCURID != 0 order by TCURID";
                    DbDataAdapter.Fill(DbDataSet, "TELECONTROL_USERS_REF");
                    foreach (DataRow DbDataRow in DbDataSet.Tables["TELECONTROL_USERS_REF"].Rows)
                    {
                        Idx = cMain.AccessList.Length;
                        Array.Resize(ref cMain.AccessList, Idx + 1);
                        cMain.AccessList[Idx].ItemAction.DBExist = true;
                        cMain.AccessList[Idx].ItemAction.Changed = false;
                        cMain.AccessList[Idx].ItemAction.Deleted = false;
                        cMain.AccessList[Idx].ID = -1;
                        cMain.AccessList[Idx].Caption = "";

                        if (DbDataRow["TCURID"] != null && DbDataRow["TCURID"].GetType() != typeof(DBNull))
                            cMain.AccessList[Idx].ID = Convert.ToInt32(DbDataRow["TCURID"].ToString());
                        if (DbDataRow["TCURACCESSNAME"] != null && DbDataRow["TCURACCESSNAME"].GetType() != typeof(DBNull))
                            cMain.AccessList[Idx].Caption = DbDataRow["TCURACCESSNAME"].ToString();                        
                    }
                    Result = true;
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return Result;
        }
        //Загрузка территориальных объединений
        private static Boolean LoadDC()
        {
            OleDbCommand DbCommand;
            OleDbDataAdapter DbDataAdapter;
            DataSet DbDataSet;
            Boolean Result = false;
            Int32 Idx;

            cMain.DC = new cMain.DC_ITEM[0];
            if (DbConnect != null)
            {
                try
                {
                    //Загрузка территориальных объединений
                    DbCommand = DbConnect.CreateCommand();
                    DbDataAdapter = new OleDbDataAdapter(DbCommand);
                    DbDataSet = new DataSet();                    
                    DbCommand.CommandText = "select * from DC order by NAME";
                    DbDataAdapter.Fill(DbDataSet, "DC");
                    foreach (DataRow DbDataRow in DbDataSet.Tables["DC"].Rows)
                    {
                        Idx = cMain.DC.Length;
                        Array.Resize(ref cMain.DC, Idx + 1);
                        cMain.DC[Idx].ItemAction.DBExist = true;
                        cMain.DC[Idx].ItemAction.Changed = false;
                        cMain.DC[Idx].ItemAction.Deleted = false;
                        cMain.DC[Idx].ParentID = -1;
                        cMain.DC[Idx].ID = -1;
                        cMain.DC[Idx].Caption = "";

                        if (DbDataRow["PARENT"] != null && DbDataRow["PARENT"].GetType() != typeof(DBNull))
                            cMain.DC[Idx].ParentID = Convert.ToInt32(DbDataRow["PARENT"].ToString());
                        if (DbDataRow["ID"] != null && DbDataRow["ID"].GetType() != typeof(DBNull))
                            cMain.DC[Idx].ID = Convert.ToInt32(DbDataRow["ID"].ToString());
                        if (DbDataRow["NAME"] != null && DbDataRow["NAME"].GetType() != typeof(DBNull))
                            cMain.DC[Idx].Caption = DbDataRow["NAME"].ToString();
                    }
                    Result = true;
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return Result;
        }
        //Загрузка объектов учета
        private static Boolean LoadObjects()
        {
            OleDbCommand DbCommand;
            OleDbDataAdapter DbDataAdapter;
            DataSet DbDataSet;
            Boolean Result = false;
            Int32 Idx;

            cMain.Objects = new cMain.OBJECT[0];
            if (DbConnect != null)
            {
                try
                {
                    //Загрузка объектов учета
                    DbCommand = DbConnect.CreateCommand();
                    DbDataAdapter = new OleDbDataAdapter(DbCommand);
                    DbDataSet = new DataSet();
                    DbCommand.CommandText = "select * from DSROBJ order by NAME";
                    DbDataAdapter.Fill(DbDataSet, "DSROBJ");

                    cGroup.Network.Objects = new cGroup.OBJECT[DbDataSet.Tables["DSROBJ"].Rows.Count];
                    int oidx = 0;
                    foreach (DataRow DbDataRow in DbDataSet.Tables["DSROBJ"].Rows)
                    {
                        Idx = cMain.Objects.Length;
                        Array.Resize(ref cMain.Objects, Idx + 1);
                        cMain.ResetObject(ref cMain.Objects[Idx]);

                        

                        cMain.Objects[Idx].ItemAction.DBExist = true;
                        if (DbDataRow["DCID"] != null && DbDataRow["DCID"].GetType() != typeof(DBNull))
                            cMain.Objects[Idx].DCID = Convert.ToInt32(DbDataRow["DCID"].ToString());
                        if (DbDataRow["OBJID"] != null && DbDataRow["OBJID"].GetType() != typeof(DBNull))
                            cMain.Objects[Idx].ID = Convert.ToInt32(DbDataRow["OBJID"].ToString());

                        if (DbDataRow["NAME"] != null && DbDataRow["NAME"].GetType() != typeof(DBNull))
                            cGroup.Network.Objects[oidx].Caption = 
                                cMain.Objects[Idx].Caption = DbDataRow["NAME"].ToString();

                        if (DbDataRow["GATE"] != null && DbDataRow["GATE"].GetType() != typeof(DBNull))
                            cMain.Objects[Idx].ComputerAddress = Convert.ToInt32(DbDataRow["GATE"].ToString());
                        if (DbDataRow["FCHAN"] != null && DbDataRow["FCHAN"].GetType() != typeof(DBNull))
                            cMain.Objects[Idx].CommChan = Convert.ToInt32(DbDataRow["FCHAN"].ToString());
                        if (DbDataRow["RCHAN"] != null && DbDataRow["RCHAN"].GetType() != typeof(DBNull))
                            cMain.Objects[Idx].AddCommChan = Convert.ToInt32(DbDataRow["RCHAN"].ToString());
                        cMain.Objects[Idx].CollectionState = false;
                        if (DbDataRow["ISACTIVE"] != null && DbDataRow["ISACTIVE"].GetType() != typeof(DBNull))
                        {
                            if (Convert.ToByte(DbDataRow["ISACTIVE"].ToString()) > 0)
                                cMain.Objects[Idx].CollectionState = true;
                        }
                        if (DbDataRow["DATESTART"] != null && DbDataRow["DATESTART"].GetType() != typeof(DBNull))
                        {
                            cMain.Objects[Idx].CollectionStartDT = Convert.ToDateTime(DbDataRow["DATESTART"].ToString());

                            if (cMain.Objects[Idx].CollectionStartDT.Year < 99)
                                cMain.Objects[Idx].CollectionStartDT = cMain.Objects[Idx].CollectionStartDT.AddYears(2000);
                        }

                        if (DbDataRow["TCPERIODTYPE"] != null && DbDataRow["TCPERIODTYPE"].GetType() != typeof(DBNull))
                            cMain.Objects[Idx].tcPeriodType = Convert.ToByte(DbDataRow["TCPERIODTYPE"].ToString());
                        if (DbDataRow["TCPERIODCOUNT"] != null && DbDataRow["TCPERIODCOUNT"].GetType() != typeof(DBNull))
                            cMain.Objects[Idx].tcPeriodCount = Convert.ToUInt16(DbDataRow["TCPERIODCOUNT"].ToString());
                        if (DbDataRow["NPATS_ID"] != null && DbDataRow["NPATS_ID"].GetType() != typeof(DBNull))
                            cMain.Objects[Idx].CodeNPATS = DbDataRow["NPATS_ID"].ToString();
                        if (DbDataRow["KOD63002"] != null && DbDataRow["KOD63002"].GetType() != typeof(DBNull))
                            cMain.Objects[Idx].Code63002 = DbDataRow["KOD63002"].ToString();
                        if (DbDataRow["EXPORTACTIVE"] != null && DbDataRow["EXPORTACTIVE"].GetType() != typeof(DBNull))
                        {
                            if (Convert.ToByte(DbDataRow["EXPORTACTIVE"].ToString()) > 0)
                                cMain.Objects[Idx].IsExported = true;
                        }
                        if (DbDataRow["DCIDEXP"] != null && DbDataRow["DCIDEXP"].GetType() != typeof(DBNull))
                            cMain.Objects[Idx].ExportDCID = Convert.ToInt32(DbDataRow["DCIDEXP"].ToString());
                        if (DbDataRow["OBJIDEXP"] != null && DbDataRow["OBJIDEXP"].GetType() != typeof(DBNull))
                            cMain.Objects[Idx].ExportObjID = Convert.ToInt32(DbDataRow["OBJIDEXP"].ToString());

                        cGroup.Network.Objects[oidx++].Object = cMain.Objects[Idx];
                        
                    }
                    Result = true;
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return Result;
        }
        //Загрузка расписания сбора объектов учета
        private static Boolean LoadObjectSchedule(Int32 ObjIdx)
        {
            OleDbCommand DbCommand;
            OleDbDataAdapter DbDataAdapter;
            DataSet DbDataSet;
            Boolean Result = false;
            Int32 i, j, ScheduleID;

            if ((ObjIdx >= 0) && (ObjIdx < cMain.Objects.Length))
            {
                if (DbConnect != null)
                {
                    try
                    {
                        for (i = 0; i < cMain.Objects[ObjIdx].Schedule.Length; i++)
                        {
                            cMain.Objects[ObjIdx].Schedule[i].CPeriodType = 0;
                            cMain.Objects[ObjIdx].Schedule[i].CPeriodCount = 0;
                        }
                        DbCommand = DbConnect.CreateCommand();
                        DbDataAdapter = new OleDbDataAdapter(DbCommand);
                        DbDataSet = new DataSet();
                        DbCommand.CommandText = "select * from SCHEDULE where DCID=" + cMain.Objects[ObjIdx].DCID.ToString() + " and OBJID=" + cMain.Objects[ObjIdx].ID.ToString() + " order by SHEDID";
                        DbDataAdapter.Fill(DbDataSet, "SCHEDULE");
                        j = 0;
                        foreach (DataRow DbDataRow in DbDataSet.Tables["SCHEDULE"].Rows)
                        {
                            if (DbDataRow["SHEDID"] != null && DbDataRow["SHEDID"].GetType() != typeof(DBNull))
                                ScheduleID = Convert.ToInt32(DbDataRow["SHEDID"].ToString());
                            else ScheduleID = -1;

                            for (i = 0; i < cMain.Objects[ObjIdx].Schedule.Length; i++)
                            {
                                if (cMain.Objects[ObjIdx].Schedule[i].ID == ScheduleID)
                                {
                                    if (ScheduleID == 1)
                                    {
                                        if (DbDataRow["SACTIVE"] != null && DbDataRow["SACTIVE"].GetType() != typeof(DBNull))
                                        {
                                            if (Convert.ToByte(DbDataRow["SACTIVE"].ToString()) > 0)
                                                cMain.Objects[ObjIdx].Schedule[i + j].CollectOn = true;
                                            else cMain.Objects[ObjIdx].Schedule[i + j].CollectOn = false;
                                        }
                                        if (DbDataRow["PERTYPECOLL"] != null && DbDataRow["PERTYPECOLL"].GetType() != typeof(DBNull))
                                            cMain.Objects[ObjIdx].Schedule[i + j].CPeriodType = Convert.ToByte(DbDataRow["PERTYPECOLL"].ToString());
                                        if (DbDataRow["PERIODCOLL"] != null && DbDataRow["PERIODCOLL"].GetType() != typeof(DBNull))
                                            cMain.Objects[ObjIdx].Schedule[i + j].CPeriodCount = Convert.ToUInt16(DbDataRow["PERIODCOLL"].ToString());
                                        if (DbDataRow["PERTYPEDATA"] != null && DbDataRow["PERTYPEDATA"].GetType() != typeof(DBNull))
                                        {
                                            cMain.Objects[ObjIdx].Schedule[i + j].PeriodTypeID = Convert.ToByte(DbDataRow["PERTYPEDATA"].ToString());
                                            cMain.Objects[ObjIdx].Schedule[i + j].DPeriodType = cMain.Objects[ObjIdx].Schedule[i + j].PeriodTypeID;
                                        }
                                        if (DbDataRow["PERIODDATA"] != null && DbDataRow["PERIODDATA"].GetType() != typeof(DBNull))
                                        {
                                            cMain.Objects[ObjIdx].Schedule[i + j].PeriodCountID = Convert.ToUInt16(DbDataRow["PERIODDATA"].ToString());
                                            cMain.Objects[ObjIdx].Schedule[i + j].DPeriodCount = cMain.Objects[ObjIdx].Schedule[i + j].PeriodCountID;
                                        }
                                        if (DbDataRow["DEPTHTYPECOLLHOLES"] != null && DbDataRow["DEPTHTYPECOLLHOLES"].GetType() != typeof(DBNull))
                                            cMain.Objects[ObjIdx].Schedule[i + j].HPeriodType = Convert.ToByte(DbDataRow["DEPTHTYPECOLLHOLES"].ToString());
                                        if (DbDataRow["DEPTHCOLLHOLES"] != null && DbDataRow["DEPTHCOLLHOLES"].GetType() != typeof(DBNull))
                                            cMain.Objects[ObjIdx].Schedule[i + j].HPeriodCount = Convert.ToUInt16(DbDataRow["DEPTHCOLLHOLES"].ToString());
                                        j++;
                                    }
                                    else
                                    {
                                        if (DbDataRow["SACTIVE"] != null && DbDataRow["SACTIVE"].GetType() != typeof(DBNull))
                                        {
                                            int temp = Convert.ToByte(DbDataRow["SACTIVE"].ToString());
 
                                            if (Convert.ToByte(DbDataRow["SACTIVE"].ToString()) > 0)
                                                cMain.Objects[ObjIdx].Schedule[i].CollectOn = true;
                                            else cMain.Objects[ObjIdx].Schedule[i].CollectOn = false;
                                        }
                                        if (DbDataRow["PERTYPECOLL"] != null && DbDataRow["PERTYPECOLL"].GetType() != typeof(DBNull))
                                            cMain.Objects[ObjIdx].Schedule[i].CPeriodType = Convert.ToByte(DbDataRow["PERTYPECOLL"].ToString());
                                        if (DbDataRow["PERIODCOLL"] != null && DbDataRow["PERIODCOLL"].GetType() != typeof(DBNull))
                                            cMain.Objects[ObjIdx].Schedule[i].CPeriodCount = Convert.ToUInt16(DbDataRow["PERIODCOLL"].ToString());
                                        if (DbDataRow["PERTYPEDATA"] != null && DbDataRow["PERTYPEDATA"].GetType() != typeof(DBNull))
                                        {
                                            cMain.Objects[ObjIdx].Schedule[i].PeriodTypeID = Convert.ToByte(DbDataRow["PERTYPEDATA"].ToString());
                                            cMain.Objects[ObjIdx].Schedule[i].DPeriodType = cMain.Objects[ObjIdx].Schedule[i].PeriodTypeID;
                                        }
                                        if (DbDataRow["PERIODDATA"] != null && DbDataRow["PERIODDATA"].GetType() != typeof(DBNull))
                                        {
                                            cMain.Objects[ObjIdx].Schedule[i].PeriodCountID = Convert.ToUInt16(DbDataRow["PERIODDATA"].ToString());
                                            cMain.Objects[ObjIdx].Schedule[i].DPeriodCount = cMain.Objects[ObjIdx].Schedule[i].PeriodCountID;
                                        }
                                        if (DbDataRow["DEPTHTYPECOLLHOLES"] != null && DbDataRow["DEPTHTYPECOLLHOLES"].GetType() != typeof(DBNull))
                                            cMain.Objects[ObjIdx].Schedule[i].HPeriodType = Convert.ToByte(DbDataRow["DEPTHTYPECOLLHOLES"].ToString());
                                        if (DbDataRow["DEPTHCOLLHOLES"] != null && DbDataRow["DEPTHCOLLHOLES"].GetType() != typeof(DBNull))
                                            cMain.Objects[ObjIdx].Schedule[i].HPeriodCount = Convert.ToUInt16(DbDataRow["DEPTHCOLLHOLES"].ToString());
                                    }
                                    break;
                                }
                            }
                        }                        
                        Result = true;
                    }
                    catch (Exception e) 
                    { 
                        Result = false; 
                        MessageBox.Show(e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);                    
                    }
                }
            }
            return Result;
        }

       


        //Загрузка устройств объектов учета
        private static Boolean LoadObjectDevices(Int32 ObjIdx)
        {
            OleDbCommand dbCommand;
            OleDbDataAdapter dbDataAdapter;
            DataSet dbDataSet;
            Boolean result = false;
            Int32 devIdx;
            int commChanIdx = -1;

            if ((ObjIdx >= 0) && (ObjIdx < cMain.Objects.Length))
            {
                cMain.Objects[ObjIdx].Device = new cMain.DEVICE[0];
                if (DbConnect != null)
                {
                    try
                    {
                        dbCommand = DbConnect.CreateCommand();
                        dbDataAdapter = new OleDbDataAdapter(dbCommand);
                        dbDataSet = new DataSet();
                        dbCommand.CommandText = "select * from DEVICES where DCID=" + cMain.Objects[ObjIdx].DCID.ToString() + " and OBJID=" + cMain.Objects[ObjIdx].ID.ToString() + " order by DEVID";
                        dbDataAdapter.Fill(dbDataSet, "DEVICES");

                        cGroup.Network.Objects[ObjIdx].Devices = new cGroup.DEVICE[dbDataSet.Tables["DEVICES"].Rows.Count];

                        foreach (DataRow dbDataRow in dbDataSet.Tables["DEVICES"].Rows)
                        {
                            devIdx = cMain.Objects[ObjIdx].Device.Length;
                            Array.Resize(ref cMain.Objects[ObjIdx].Device, devIdx + 1);
                            cMain.ResetDevice(ref cMain.Objects[ObjIdx].Device[devIdx]);

                            cMain.Objects[ObjIdx].Device[devIdx].ItemAction.DBExist = true;
                            if (dbDataRow["DEVINC"] != null && dbDataRow["DEVINC"].GetType() != typeof(DBNull))
                                cMain.Objects[ObjIdx].Device[devIdx].ID = Convert.ToInt32(dbDataRow["DEVINC"].ToString());

                            if (dbDataRow["DEVICE"] != null && dbDataRow["DEVICE"].GetType() != typeof(DBNull))
                                cMain.Objects[ObjIdx].Device[devIdx].DeviceID = Convert.ToInt32(dbDataRow["DEVICE"].ToString());

                            if (dbDataRow["NET"] != null && dbDataRow["NET"].GetType() != typeof(DBNull))
                                cMain.Objects[ObjIdx].Device[devIdx].NetAddress = Convert.ToInt32(dbDataRow["NET"].ToString());

                            if (dbDataRow["DEVID"] != null && dbDataRow["DEVID"].GetType() != typeof(DBNull))
                                cMain.Objects[ObjIdx].Device[devIdx].Address = Convert.ToInt32(dbDataRow["DEVID"].ToString());

                            if (dbDataRow["IDENTIFIER"] != null && dbDataRow["IDENTIFIER"].GetType() != typeof(DBNull))
                                cMain.Objects[ObjIdx].Device[devIdx].Identifier = dbDataRow["IDENTIFIER"].ToString();

                            if (dbDataRow["SERNUM"] != null && dbDataRow["SERNUM"].GetType() != typeof(DBNull))
                                cMain.Objects[ObjIdx].Device[devIdx].SerialNumber = dbDataRow["SERNUM"].ToString();

                            if (dbDataRow["LOGDATEEND"] != null && dbDataRow["LOGDATEEND"].GetType() != typeof(DBNull))
                                cMain.Objects[ObjIdx].Device[devIdx].JournalLastDT = Convert.ToDateTime(dbDataRow["LOGDATEEND"].ToString());

                            if (dbDataRow["LASTEVENTNUMBER"] != null && dbDataRow["LASTEVENTNUMBER"].GetType() != typeof(DBNull))
                                cMain.Objects[ObjIdx].Device[devIdx].LastEventIdx = Convert.ToInt32(dbDataRow["LASTEVENTNUMBER"].ToString());

                            if (dbDataRow["EXPORTACTIVE"] != null && dbDataRow["EXPORTACTIVE"].GetType() != typeof(DBNull))
                            {
                                if (Convert.ToByte(dbDataRow["EXPORTACTIVE"].ToString()) > 0)
                                    cMain.Objects[ObjIdx].Device[devIdx].IsExported = true;
                                else cMain.Objects[ObjIdx].Device[devIdx].IsExported = false;
                            }
                            if (dbDataRow["LOGIN"] != null && dbDataRow["LOGIN"].GetType() != typeof(DBNull))
                                cMain.Objects[ObjIdx].Device[devIdx].UserName = dbDataRow["LOGIN"].ToString();

                            if (dbDataRow["PASS"] != null && dbDataRow["PASS"].GetType() != typeof(DBNull))
                                cMain.Objects[ObjIdx].Device[devIdx].UserPassword = dbDataRow["PASS"].ToString();

                            //Настройки протокола обмена                            
                            if (dbDataRow["SETTINGS"] != null && dbDataRow["SETTINGS"].GetType() != typeof(DBNull))                            
                                cMain.Objects[ObjIdx].Device[devIdx].ProtocolSetting = (Byte[])dbDataRow["SETTINGS"];

                            cGroup.Network.Objects[ObjIdx].Devices[devIdx].DBDeviceInfo = cMain.Objects[ObjIdx].Device[devIdx];
                            cGroup.Network.Objects[ObjIdx].Devices[devIdx].DevtypeSettingInx = getDevtypeSettingInx(cMain.Objects[ObjIdx].Device[devIdx].DeviceID);
                            cGroup.Network.Objects[ObjIdx].Devices[devIdx].Address = cMain.Objects[ObjIdx].Device[devIdx].Address >= 0 ? (uint)cMain.Objects[ObjIdx].Device[devIdx].Address : 0;
                            
                            if (cGroup.Network.Protocol == null)
                                cGroup.Network.Protocol = new cGroup.MODULE_SETTING[1];
                            else
                                Array.Resize(ref cGroup.Network.Protocol, cGroup.Network.Protocol.Length + 1);

                            if (cGroup.Network.Objects[ObjIdx].Devices[devIdx].DevtypeSettingInx != -1)
                            {
                                cGroup.Network.Protocol[cGroup.Network.ProtocolCount].TypeDescription =
                                    cMain.DevTypeList[cGroup.Network.Objects[ObjIdx].Devices[devIdx].DevtypeSettingInx].ProtocolDLLName.Substring(0,
                                    cMain.DevTypeList[cGroup.Network.Objects[ObjIdx].Devices[devIdx].DevtypeSettingInx].ProtocolDLLName.IndexOf('.', 0));

                                cGroup.Network.Protocol[cGroup.Network.ProtocolCount].Caption = 
                                    cMain.DevTypeList[cGroup.Network.Objects[ObjIdx].Devices[devIdx].DevtypeSettingInx].Caption;
                                cGroup.Network.Protocol[cGroup.Network.ProtocolCount].Setting = 
                                    cMain.DevTypeList[cGroup.Network.Objects[ObjIdx].Devices[devIdx].DevtypeSettingInx].ProtocolSetting;

                                cGroup.Network.Objects[ObjIdx].Devices[devIdx].ProtocolID = 
                                    cGroup.Network.Protocol[cGroup.Network.ProtocolCount].ID = cGroup.Network.ProtocolCount++;

                                cGroup.Network.Objects[ObjIdx].Devices[devIdx].CommChanID = getCommChanInxForID(cMain.Objects[ObjIdx].CommChan);
                            }

                        
                            
                        }
                        result = true;
                    }
                    catch (Exception e) 
                    { 
                        MessageBox.Show(e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            return result;
        }

        public static int getDevtypeSettingInx(int deviceID)
        {
            for (int i = 0; i < cMain.DevTypeList.Length; i++)
            {
                if (cMain.DevTypeList[i].ID == deviceID)
                    return i;
            }
            return -1;
        }

        public static int getCommChanInxForID(int id)
        {
            for (int i = 0; i < cMain.CommChanList.Length; i++)
            {

                if (cGroup.Network.CommChan[i].SettingsInDB.ID == id)
                    return i;
            }
            return -1;
        }
        //Загрузка списка коммутационного оборудования для устройства
        private static Boolean LoadDeviceCommEqupment(Int32 ObjIdx, Int32 DevIdx)
        {
            OleDbCommand DbCommand;
            OleDbDataAdapter DbDataAdapter;
            DataSet DbDataSet;
            Boolean Result = false;
            Int32 Idx;

            if ((ObjIdx >= 0) && (ObjIdx < cMain.Objects.Length))
            {
                if ((DevIdx >= 0) && (DevIdx < cMain.Objects[ObjIdx].Device.Length))
                {
                    cMain.Objects[ObjIdx].Device[DevIdx].CommEquipment = new cMain.COMMUTATION_EQUIPMENT[0];
                    if (DbConnect != null)
                    {
                        try
                        {
                            DbCommand = DbConnect.CreateCommand();
                            DbDataAdapter = new OleDbDataAdapter(DbCommand);
                            DbDataSet = new DataSet();
                            DbCommand.CommandText = "select * from IDC_STATE where DCID=" + 
                                cMain.Objects[ObjIdx].DCID.ToString() + " and OBJID=" + 
                                cMain.Objects[ObjIdx].ID.ToString() + " and DEVINC=" + 
                                cMain.Objects[ObjIdx].Device[DevIdx].ID.ToString() + " order by IDSTATE";

                            DbDataAdapter.Fill(DbDataSet, "IDC_STATE");
                            foreach (DataRow DbDataRow in DbDataSet.Tables["IDC_STATE"].Rows)
                            {
                                Idx = cMain.Objects[ObjIdx].Device[DevIdx].CommEquipment.Length;
                                Array.Resize(ref cMain.Objects[ObjIdx].Device[DevIdx].CommEquipment, Idx + 1);

                                cMain.Objects[ObjIdx].Device[DevIdx].CommEquipment[Idx].ItemAction.DBExist = true;
                                cMain.Objects[ObjIdx].Device[DevIdx].CommEquipment[Idx].ItemAction.Deleted = false;
                                cMain.Objects[ObjIdx].Device[DevIdx].CommEquipment[Idx].ItemAction.Changed = false;
                                cMain.Objects[ObjIdx].Device[DevIdx].CommEquipment[Idx].ID = -1;
                                cMain.Objects[ObjIdx].Device[DevIdx].CommEquipment[Idx].ChannelNumber = -1;
                                cMain.Objects[ObjIdx].Device[DevIdx].CommEquipment[Idx].Caption = "";

                                if (DbDataRow["IDINC"] != null && DbDataRow["IDINC"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].CommEquipment[Idx].ID = Convert.ToInt32(DbDataRow["IDINC"].ToString());
                                if (DbDataRow["IDSTATE"] != null && DbDataRow["IDSTATE"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].CommEquipment[Idx].ChannelNumber = Convert.ToInt32(DbDataRow["IDSTATE"].ToString());
                                if (DbDataRow["NAME"] != null && DbDataRow["NAME"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].CommEquipment[Idx].Caption = DbDataRow["NAME"].ToString(); 
                            }
                            Result = true;
                        }
                        catch (Exception e) 
                        { 
                            MessageBox.Show(e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
            return Result;
        }
        //Загрузка присоединений устройства
        private static Boolean LoadDeviceJoins(Int32 ObjIdx, Int32 DevIdx)
        {
            OleDbCommand DbCommand;
            OleDbDataAdapter DbDataAdapter;
            DataSet DbDataSet;
            Boolean Result = false;
            Int32 Idx;

            if ((ObjIdx >= 0) && (ObjIdx < cMain.Objects.Length))
            {
                if ((DevIdx >= 0) && (DevIdx < cMain.Objects[ObjIdx].Device.Length))
                {
                    cMain.Objects[ObjIdx].Device[DevIdx].Join = new cMain.JOIN[0];
                    if (DbConnect != null)
                    {
                        try
                        {
                            DbCommand = DbConnect.CreateCommand();
                            DbDataAdapter = new OleDbDataAdapter(DbCommand);
                            DbDataSet = new DataSet();
                            DbCommand.CommandText = "select * from JOINS where DCID=" + cMain.Objects[ObjIdx].DCID.ToString() + " and OBJID=" + cMain.Objects[ObjIdx].ID.ToString() + " and DEVINC=" + cMain.Objects[ObjIdx].Device[DevIdx].ID.ToString() + " order by JOINID";//TITLE";
                            DbDataAdapter.Fill(DbDataSet, "JOINS");
                            foreach (DataRow DbDataRow in DbDataSet.Tables["JOINS"].Rows)
                            {
                                Idx = cMain.Objects[ObjIdx].Device[DevIdx].Join.Length;
                                Array.Resize(ref cMain.Objects[ObjIdx].Device[DevIdx].Join, Idx + 1);
                                cMain.ResetJoin(ref cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx]);
                                
                                cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].ItemAction.DBExist = true;

                                if (DbDataRow["DEVID"] != null && DbDataRow["DEVID"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].DeviceID = Convert.ToInt32(DbDataRow["DEVID"].ToString());
                                if (DbDataRow["JOINID"] != null && DbDataRow["JOINID"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].ID = Convert.ToInt32(DbDataRow["JOINID"].ToString());
                                if (DbDataRow["JOININC"] != null && DbDataRow["JOININC"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].Index = Convert.ToInt32(DbDataRow["JOININC"].ToString());
                                if (DbDataRow["TITLE"] != null && DbDataRow["TITLE"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].Caption = DbDataRow["TITLE"].ToString();
                                if (DbDataRow["METERNUMBER"] != null && DbDataRow["METERNUMBER"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].MeterNumber = Convert.ToInt32(DbDataRow["METERNUMBER"].ToString());
                                if (DbDataRow["ENABLED"] != null && DbDataRow["ENABLED"].GetType() != typeof(DBNull))
                                {
                                    if (Convert.ToByte(DbDataRow["ENABLED"].ToString()) > 0)
                                        cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].CollectEnable = true;
                                    else cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].CollectEnable = false;
                                }
                                if (DbDataRow["RECALC"] != null && DbDataRow["RECALC"].GetType() != typeof(DBNull))
                                {
                                    if (Convert.ToByte(DbDataRow["RECALC"].ToString()) > 0)
                                        cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].CoeffMultiply = true;
                                    else cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].CoeffMultiply = false;
                                }
                                if (DbDataRow["TRANS_VQE"] != null && DbDataRow["TRANS_VQE"].GetType() != typeof(DBNull))
                                {
                                    if (Convert.ToByte(DbDataRow["TRANS_VQE"].ToString()) > 0)
                                        cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].ConvertParam = true;
                                    else cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].ConvertParam = false;
                                }
                                if (DbDataRow["KTT"] != null && DbDataRow["KTT"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].KTT = Convert.ToUInt16(DbDataRow["KTT"].ToString());
                                if (DbDataRow["KTN"] != null && DbDataRow["KTN"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].KTN = Convert.ToUInt16(DbDataRow["KTN"].ToString());
                                if (DbDataRow["PTT"] != null && DbDataRow["PTT"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].KTTClass = Convert.ToDouble(DbDataRow["PTT"].ToString());
                                if (DbDataRow["PTN"] != null && DbDataRow["PTN"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].KTNClass = Convert.ToDouble(DbDataRow["PTN"].ToString());
                                if (DbDataRow["DPXX"] != null && DbDataRow["DPXX"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].IdlingLosts = Convert.ToDouble(DbDataRow["DPXX"].ToString());
                                if (DbDataRow["DPKZ"] != null && DbDataRow["DPKZ"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].ShortCircuitLosts = Convert.ToDouble(DbDataRow["DPKZ"].ToString());
                                if (DbDataRow["SNOM"] != null && DbDataRow["SNOM"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].TransformatorPower = Convert.ToDouble(DbDataRow["SNOM"].ToString());
                                if (DbDataRow["LOSS_IN_COUNTER"] != null && DbDataRow["LOSS_IN_COUNTER"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].MeterLostsValue = Convert.ToDouble(DbDataRow["LOSS_IN_COUNTER"].ToString());
                                if (DbDataRow["LOSS_IN_TT"] != null && DbDataRow["LOSS_IN_TT"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].TTLostsValue = Convert.ToDouble(DbDataRow["LOSS_IN_TT"].ToString());
                                if (DbDataRow["LOSS_IN_TN"] != null && DbDataRow["LOSS_IN_TN"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].TNLostsValue = Convert.ToDouble(DbDataRow["LOSS_IN_TN"].ToString());

                                if (DbDataRow["NPATS_TYPE"] != null && DbDataRow["NPATS_TYPE"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].MeterCodeHPATS = DbDataRow["NPATS_TYPE"].ToString();
                                if (DbDataRow["NPATS_ID"] != null && DbDataRow["NPATS_ID"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].ExportCodeHPATS = DbDataRow["NPATS_ID"].ToString();
                                if (DbDataRow["NPATS_ID_IMP"] != null && DbDataRow["NPATS_ID_IMP"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].ImportCodeHPATS = DbDataRow["NPATS_ID_IMP"].ToString();
                                if (DbDataRow["ADDRESS"] != null && DbDataRow["ADDRESS"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].CollectPointAddress = DbDataRow["ADDRESS"].ToString();
                                if (DbDataRow["PLANTPLACE"] != null && DbDataRow["PLANTPLACE"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].MeterPlacement = DbDataRow["PLANTPLACE"].ToString();
                                if (DbDataRow["COMMENTS"] != null && DbDataRow["COMMENTS"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].Comments = DbDataRow["COMMENTS"].ToString();
                                if (DbDataRow["SUBSCRIBER"] != null && DbDataRow["SUBSCRIBER"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].AbonentNumber = DbDataRow["SUBSCRIBER"].ToString();
                                if (DbDataRow["TREATY"] != null && DbDataRow["TREATY"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].AgreementNumber = DbDataRow["TREATY"].ToString();
                                if (DbDataRow["RECEIPTMETHOD"] != null && DbDataRow["RECEIPTMETHOD"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].EvidenceMetod = DbDataRow["RECEIPTMETHOD"].ToString();
                                if (DbDataRow["BALANCEATTRIB"] != null && DbDataRow["BALANCEATTRIB"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].BalanceBelonging = DbDataRow["BALANCEATTRIB"].ToString();
                                if (DbDataRow["DIRECTOR"] != null && DbDataRow["DIRECTOR"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].Director = DbDataRow["DIRECTOR"].ToString();
                                if (DbDataRow["POWERSPEC"] != null && DbDataRow["POWERSPEC"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].GeneralPES = DbDataRow["POWERSPEC"].ToString();
                                if (DbDataRow["PHONE"] != null && DbDataRow["PHONE"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].PhoneNumber = DbDataRow["PHONE"].ToString();
                                if (DbDataRow["CHECKDATE"] != null && DbDataRow["CHECKDATE"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].DTLastInspection = Convert.ToDateTime(DbDataRow["CHECKDATE"].ToString());
                                if (DbDataRow["SUBABONENT"] != null && DbDataRow["SUBABONENT"].GetType() != typeof(DBNull))
                                {
                                    if (Convert.ToByte(DbDataRow["SUBABONENT"].ToString()) > 0)
                                        cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].InSubscriberGroup = true;
                                    else cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].InSubscriberGroup = false;
                                }
                                if (DbDataRow["KPE"] != null && DbDataRow["KPE"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].KPE = Convert.ToDouble(DbDataRow["KPE"].ToString());
                                if (DbDataRow["KPM"] != null && DbDataRow["KPM"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].KPM = Convert.ToDouble(DbDataRow["KPM"].ToString());
                                if (DbDataRow["TARIFFVOLTAGE"] != null && DbDataRow["TARIFFVOLTAGE"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].UTariffLevel = Convert.ToDouble(DbDataRow["TARIFFVOLTAGE"].ToString());
                                if (DbDataRow["VOLTAGE"] != null && DbDataRow["VOLTAGE"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].UTransformator = Convert.ToDouble(DbDataRow["VOLTAGE"].ToString());
                                if (DbDataRow["LOSS_IN_TRANS"] != null && DbDataRow["LOSS_IN_TRANS"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].TransformatorLosts = Convert.ToDouble(DbDataRow["LOSS_IN_TRANS"].ToString());
                                if (DbDataRow["LOSS_IN_LINE"] != null && DbDataRow["LOSS_IN_LINE"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].LineLosts = Convert.ToDouble(DbDataRow["LOSS_IN_LINE"].ToString());
                                if (DbDataRow["TT_TYPE"] != null && DbDataRow["TT_TYPE"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].ITransformatorType = DbDataRow["TT_TYPE"].ToString();
                                if (DbDataRow["TT_CURRENT1"] != null && DbDataRow["TT_CURRENT1"].GetType() != typeof(DBNull)) 
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].INominalFirstTT = Convert.ToDouble(DbDataRow["TT_CURRENT1"].ToString());
                                if (DbDataRow["TT_CURRENT2"] != null && DbDataRow["TT_CURRENT2"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].INominalSecondTT = Convert.ToDouble(DbDataRow["TT_CURRENT2"].ToString());
                                if (DbDataRow["TN_TYPE"] != null && DbDataRow["TN_TYPE"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].UTransformatorType = DbDataRow["TN_TYPE"].ToString();
                                if (DbDataRow["TN_VOLTAGE1"] != null && DbDataRow["TN_VOLTAGE1"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].UNominalFirstTT = Convert.ToDouble(DbDataRow["TN_VOLTAGE1"].ToString());
                                if (DbDataRow["TN_VOLTAGE2"] != null && DbDataRow["TN_VOLTAGE2"].GetType() != typeof(DBNull))
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[Idx].UNominalSecondTT = Convert.ToDouble(DbDataRow["TN_VOLTAGE2"].ToString());
                            }
                            Result = true;
                        }
                        catch (Exception e) 
                        { 
                            MessageBox.Show(e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
            return Result;
        }
        //Загрузка каналов учета присоединения
        private static Boolean LoadJoinChannels(Int32 ObjIdx, Int32 DevIdx, Int32 JoinIdx)
        {
            OleDbCommand DbCommand;
            OleDbDataAdapter DbDataAdapter;
            DataSet DbDataSet;
            Boolean Result = false;
            Int32 Idx;
            Int16 AR, Dir;

            if ((ObjIdx >= 0) && (ObjIdx < cMain.Objects.Length))
            {
                if ((DevIdx >= 0) && (DevIdx < cMain.Objects[ObjIdx].Device.Length))
                {
                    if ((JoinIdx >= 0) && (JoinIdx < cMain.Objects[ObjIdx].Device[DevIdx].Join.Length))
                    {
                        cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel = new cMain.CHANNEL[0];
                        if (DbConnect != null)
                        {
                            try
                            {
                                DbCommand = DbConnect.CreateCommand();
                                DbDataAdapter = new OleDbDataAdapter(DbCommand);
                                DbDataSet = new DataSet();
                                DbCommand.CommandText = "select * from CHANNELS where DCID=" + cMain.Objects[ObjIdx].DCID.ToString() + " and OBJID=" + cMain.Objects[ObjIdx].ID.ToString() + " and DEVID=" + cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].DeviceID.ToString() + " and JOINID=" + cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].ID.ToString() + " order by CHANID";
                                DbDataAdapter.Fill(DbDataSet, "CHANNELS");
                                foreach (DataRow DbDataRow in DbDataSet.Tables["CHANNELS"].Rows)
                                {
                                    Idx = cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel.Length;
                                    Array.Resize(ref cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel, Idx + 1);
                                    cMain.ResetChannel(ref cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel[Idx]);

                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel[Idx].ItemAction.DBExist = true;

                                    if (DbDataRow["CHANID"] != null && DbDataRow["CHANID"].GetType() != typeof(DBNull))
                                        cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel[Idx].ID = Convert.ToInt32(DbDataRow["CHANID"].ToString());
                                    if (DbDataRow["ENABLED"] != null && DbDataRow["ENABLED"].GetType() != typeof(DBNull))
                                    {
                                        if (Convert.ToByte(DbDataRow["ENABLED"].ToString()) > 0)
                                            cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel[Idx].CollectEnable = true;
                                        else cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel[Idx].CollectEnable = false;
                                    }                                    
                                    Dir = 0;
                                    AR = -1;
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel[Idx].EnergyType = (Byte)Idx;
                                    if (DbDataRow["DIRECTION"] != null && DbDataRow["DIRECTION"].GetType() != typeof(DBNull))
                                        Dir = Convert.ToInt16(DbDataRow["DIRECTION"].ToString());
                                    if (DbDataRow["AR"] != null && DbDataRow["AR"].GetType() != typeof(DBNull))
                                        AR = Convert.ToInt16(DbDataRow["AR"].ToString());
                                    switch (AR)
                                    { 
                                        case 0:
                                            if (Dir == 1) cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel[Idx].EnergyType = 0;
                                            if (Dir == -1) cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel[Idx].EnergyType = 1; 
                                            break;
                                        case 1:
                                            if (Dir == 1) cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel[Idx].EnergyType = 2;
                                            if (Dir == -1) cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel[Idx].EnergyType = 3;
                                            break;
                                        case 2:
                                            if (Dir == 1) cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel[Idx].EnergyType = 4;
                                            if (Dir == -1) cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel[Idx].EnergyType = 7;
                                            break;
                                        case 3:
                                            if (Dir == 1) cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel[Idx].EnergyType = 5;
                                            if (Dir == -1) cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel[Idx].EnergyType = 6;
                                            break;
                                        default:
                                            break;
                                    }
                                    if (DbDataRow["SERNUM"] != null && DbDataRow["SERNUM"].GetType() != typeof(DBNull))
                                        cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel[Idx].MeterSerial = DbDataRow["SERNUM"].ToString();
                                    if (DbDataRow["METER"] != null && DbDataRow["METER"].GetType() != typeof(DBNull))
                                        cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel[Idx].MeterID = Convert.ToInt32(DbDataRow["METER"].ToString());
                                    if (DbDataRow["NPATS_ID"] != null && DbDataRow["NPATS_ID"].GetType() != typeof(DBNull))
                                        cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel[Idx].ExportNPATSCode = DbDataRow["NPATS_ID"].ToString();
                                    if (DbDataRow["NPATS_ID_IMP"] != null && DbDataRow["NPATS_ID_IMP"].GetType() != typeof(DBNull))
                                        cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel[Idx].ImportNPATSCode = DbDataRow["NPATS_ID_IMP"].ToString();
                                    if (DbDataRow["TYPE63002"] != null && DbDataRow["TYPE63002"].GetType() != typeof(DBNull))
                                        cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel[Idx].Value63002Code = DbDataRow["TYPE63002"].ToString();
                                    if (DbDataRow["ASKP_ID"] != null && DbDataRow["ASKP_ID"].GetType() != typeof(DBNull))
                                        cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel[Idx].ASKPIdentifier = DbDataRow["ASKP_ID"].ToString();//Проверить
                                }
                                Result = true;
                            }
                            catch (Exception e) 
                            { 
                                MessageBox.Show(e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                }
            }
            return Result;
        }
        //Загрузка линий электропередач присоединения
        private static Boolean LoadJoinConnectionLines(Int32 ObjIdx, Int32 DevIdx, Int32 JoinIdx)
        {
            OleDbCommand DbCommand;
            OleDbDataAdapter DbDataAdapter;
            DataSet DbDataSet;
            Boolean Result = false;
            Int32 Idx;

            if ((ObjIdx >= 0) && (ObjIdx < cMain.Objects.Length))
            {
                if ((DevIdx >= 0) && (DevIdx < cMain.Objects[ObjIdx].Device.Length))
                {
                    if ((JoinIdx >= 0) && (JoinIdx < cMain.Objects[ObjIdx].Device[DevIdx].Join.Length))
                    {
                        cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].ConnLineLosts = new cMain.CONN_LINE_LOSTS[0];
                        if (DbConnect != null)
                        {
                            try
                            {
                                DbCommand = DbConnect.CreateCommand();
                                DbDataAdapter = new OleDbDataAdapter(DbCommand);
                                DbDataSet = new DataSet();
                                DbCommand.CommandText = "select * from LINES where JOININC=" + cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Index.ToString() + " order by LINEID";                                
                                DbDataAdapter.Fill(DbDataSet, "LINES");
                                foreach (DataRow DbDataRow in DbDataSet.Tables["LINES"].Rows)
                                {
                                    Idx = cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].ConnLineLosts.Length;
                                    Array.Resize(ref cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].ConnLineLosts, Idx + 1);

                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].ConnLineLosts[Idx].ItemAction.DBExist = true;
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].ConnLineLosts[Idx].ItemAction.Changed = false;
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].ConnLineLosts[Idx].ItemAction.Deleted = false;
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].ConnLineLosts[Idx].ID = -1;
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].ConnLineLosts[Idx].LineLength = 0;
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].ConnLineLosts[Idx].Resistance = 0;
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].ConnLineLosts[Idx].UNominal = 0;
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].ConnLineLosts[Idx].CableLost = 0;
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].ConnLineLosts[Idx].AirLost = 0;
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].ConnLineLosts[Idx].CircuitsAmount = 0;

                                    if (DbDataRow["LINEID"] != null && DbDataRow["LINEID"].GetType() != typeof(DBNull))
                                        cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].ConnLineLosts[Idx].ID = Convert.ToInt32(DbDataRow["LINEID"].ToString());
                                    if (DbDataRow["LENGTH"] != null && DbDataRow["LENGTH"].GetType() != typeof(DBNull))
                                        cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].ConnLineLosts[Idx].LineLength = Convert.ToDouble(DbDataRow["LENGTH"].ToString());
                                    if (DbDataRow["RESISTIVITY"] != null && DbDataRow["RESISTIVITY"].GetType() != typeof(DBNull))
                                        cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].ConnLineLosts[Idx].Resistance = Convert.ToDouble(DbDataRow["RESISTIVITY"].ToString());
                                    if (DbDataRow["VOLTAGE"] != null && DbDataRow["VOLTAGE"].GetType() != typeof(DBNull))
                                        cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].ConnLineLosts[Idx].UNominal = Convert.ToDouble(DbDataRow["VOLTAGE"].ToString());
                                    if (DbDataRow["LOSS_UD_INSN"] != null && DbDataRow["LOSS_UD_INSN"].GetType() != typeof(DBNull))
                                        cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].ConnLineLosts[Idx].CableLost = Convert.ToDouble(DbDataRow["LOSS_UD_INSN"].ToString());
                                    if (DbDataRow["LOSS_UD_INSR"] != null && DbDataRow["LOSS_UD_INSR"].GetType() != typeof(DBNull))
                                        cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].ConnLineLosts[Idx].AirLost = Convert.ToDouble(DbDataRow["LOSS_UD_INSR"].ToString());                                    
                                    if (DbDataRow["CIRCUITS_AMOUNT"] != null && DbDataRow["CIRCUITS_AMOUNT"].GetType() != typeof(DBNull))
                                        cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].ConnLineLosts[Idx].CircuitsAmount = Convert.ToInt32(DbDataRow["CIRCUITS_AMOUNT"].ToString());
                                }
                                Result = true;
                            }
                            catch (Exception e)                             
                            { 
                                MessageBox.Show(e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                }
            }
            return Result;
        }
        //Загрузка групп отчетов присоединения
        private static Boolean LoadJoinReportGroups(Int32 ObjIdx, Int32 DevIdx, Int32 JoinIdx)
        {
            OleDbCommand DbCommand;
            OleDbDataAdapter DbDataAdapter;
            DataSet DbDataSet;
            Boolean Result = false;
            Int32 Idx;

            if ((ObjIdx >= 0) && (ObjIdx < cMain.Objects.Length))
            {
                if ((DevIdx >= 0) && (DevIdx < cMain.Objects[ObjIdx].Device.Length))
                {
                    if ((JoinIdx >= 0) && (JoinIdx < cMain.Objects[ObjIdx].Device[DevIdx].Join.Length))
                    {
                        cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].ReportGroup = new cMain.REPORT_GROUP[0];
                        if (DbConnect != null)
                        {
                            try
                            {
                                DbCommand = DbConnect.CreateCommand();
                                DbDataAdapter = new OleDbDataAdapter(DbCommand);
                                DbDataSet = new DataSet();
                                DbCommand.CommandText = "select * from JOIN_GROUP where DCID=" + cMain.Objects[ObjIdx].DCID.ToString() + " and OBJID=" + cMain.Objects[ObjIdx].ID.ToString() + " and DEVID=" + cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].DeviceID.ToString() + " and JOINID=" + cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].ID.ToString();
                                DbDataAdapter.Fill(DbDataSet, "JOIN_GROUP");
                                foreach (DataRow DbDataRow in DbDataSet.Tables["JOIN_GROUP"].Rows)
                                {
                                    Idx = cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].ReportGroup.Length;
                                    Array.Resize(ref cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].ReportGroup, Idx + 1);
                                    
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].ReportGroup[Idx].ItemAction.DBExist = true;
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].ReportGroup[Idx].ItemAction.Changed = false;
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].ReportGroup[Idx].ItemAction.Deleted = false;
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].ReportGroup[Idx].ID = -1;
                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].ReportGroup[Idx].RGType = -1;

                                    if (DbDataRow["REPGROUPID"] != null && DbDataRow["REPGROUPID"].GetType() != typeof(DBNull))
                                        cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].ReportGroup[Idx].ID = Convert.ToInt32(DbDataRow["REPGROUPID"].ToString());
                                    if (DbDataRow["REPGROUP_REF"] != null && DbDataRow["REPGROUP_REF"].GetType() != typeof(DBNull))
                                        cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].ReportGroup[Idx].RGType = Convert.ToInt32(DbDataRow["REPGROUP_REF"].ToString());
                                }
                                cMain.ReportGroupList = new cMain.REPORT_GROUP_SETTING[0];
                                DbCommand.CommandText = "select * from REPORT_GROUP order by ID";
                                DbDataAdapter.Fill(DbDataSet, "REPORT_GROUP");
                                foreach (DataRow DbDataRow in DbDataSet.Tables["REPORT_GROUP"].Rows)
                                {
                                    Idx = cMain.ReportGroupList.Length;
                                    Array.Resize(ref cMain.ReportGroupList, Idx + 1);
                                    cMain.ReportGroupList[Idx].ItemAction.DBExist = true;
                                    cMain.ReportGroupList[Idx].ItemAction.Changed = false;
                                    cMain.ReportGroupList[Idx].ItemAction.Deleted = false;
                                    cMain.ReportGroupList[Idx].ID = -1;
                                    cMain.ReportGroupList[Idx].Caption = "";

                                    if (DbDataRow["ID"] != null && DbDataRow["ID"].GetType() != typeof(DBNull))
                                        cMain.ReportGroupList[Idx].ID = Convert.ToInt32(DbDataRow["ID"].ToString());
                                    if (DbDataRow["NAME"] != null && DbDataRow["NAME"].GetType() != typeof(DBNull))
                                        cMain.ReportGroupList[Idx].Caption = DbDataRow["NAME"].ToString();
                                }
                                Result = true;
                            }
                            catch (Exception e) 
                            { 
                                MessageBox.Show(e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                }
            }
            return Result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ObjIdx"></param>
        /// <param name="DevIdx"></param>
        /// <param name="JoinIdx"></param>
        /// <returns></returns>
        private static Boolean LoadFindedDevice(Int32 ObjIdx, Int32 DevIdx)
        {
            OleDbCommand DbCommand;
            OleDbDataAdapter DbDataAdapter;
            DataSet DbDataSet;

            if ((ObjIdx >= 0) && (ObjIdx < cMain.Objects.Length))
            {
                if ((DevIdx >= 0) && (DevIdx < cMain.Objects[ObjIdx].Device.Length))
                {
                    if (DbConnect != null)
                    {
                        try
                        {

                            DbCommand = DbConnect.CreateCommand();
                            DbDataAdapter = new OleDbDataAdapter(DbCommand);
                            DbDataSet = new DataSet();
                              
                            DbCommand.CommandText = "select * from CONFIG where DCID=" +
                                 cMain.Objects[ObjIdx].DCID.ToString() + "and OBJID =" +
                                 cMain.Objects[ObjIdx].ID.ToString() + "and DEVID =" +
                                 cMain.Objects[ObjIdx].Device[DevIdx].ID.ToString() + "order by DCID";

                            DbDataAdapter.Fill(DbDataSet, "CONFIG");

                            if (DbDataSet.Tables["CONFIG"].Rows != null &&
                                DbDataSet.Tables["CONFIG"].Rows.Count > 0)
                            {
                                cMain.Objects[ObjIdx].Device[DevIdx].FindedDevice = new cMain.FindedDevice[DbDataSet.Tables["CONFIG"].Rows.Count];
                                int idx = 0;

                                foreach (DataRow DbDataRow in DbDataSet.Tables["CONFIG"].Rows)
                                {

                                    cMain.Objects[ObjIdx].Device[DevIdx].FindedDevice[idx] = new cMain.FindedDevice();

                                    if (DbDataRow["dcid"] != null && DbDataRow["dcid"].GetType() != typeof(DBNull))
                                        cMain.Objects[ObjIdx].Device[DevIdx].FindedDevice[idx].DCID = Convert.ToInt32(DbDataRow["dcid"].ToString());
                                    if (DbDataRow["objid"] != null && DbDataRow["objid"].GetType() != typeof(DBNull))
                                        cMain.Objects[ObjIdx].Device[DevIdx].FindedDevice[idx].ObjectID = Convert.ToInt32(DbDataRow["objid"].ToString());
                                    if (DbDataRow["devid"] != null && DbDataRow["devid"].GetType() != typeof(DBNull))
                                        cMain.Objects[ObjIdx].Device[DevIdx].FindedDevice[idx].DeviceID = Convert.ToInt32(DbDataRow["devid"].ToString());
                                    if (DbDataRow["meter"] != null && DbDataRow["meter"].GetType() != typeof(DBNull))
                                        cMain.Objects[ObjIdx].Device[DevIdx].FindedDevice[idx].Meter = Convert.ToInt32(DbDataRow["meter"].ToString());
                                    if (DbDataRow["accessory"] != null && DbDataRow["accessory"].GetType() != typeof(DBNull))
                                        cMain.Objects[ObjIdx].Device[DevIdx].FindedDevice[idx].AccessoryCode = Convert.ToByte(DbDataRow["accessory"].ToString());
                                    if (DbDataRow["metertype"] != null && DbDataRow["metertype"].GetType() != typeof(DBNull))
                                        cMain.Objects[ObjIdx].Device[DevIdx].FindedDevice[idx].MeterTypeCode = Convert.ToByte(DbDataRow["metertype"].ToString());
                                    if (DbDataRow["sernum"] != null && DbDataRow["sernum"].GetType() != typeof(DBNull))
                                        cMain.Objects[ObjIdx].Device[DevIdx].FindedDevice[idx].MeterFactoryNum = DbDataRow["sernum"].ToString();
                                    if (DbDataRow["docnum"] != null && DbDataRow["docnum"].GetType() != typeof(DBNull))
                                        cMain.Objects[ObjIdx].Device[DevIdx].FindedDevice[idx].AbonentNum = DbDataRow["docnum"].ToString();
                                    if (DbDataRow["stamp"] != null && DbDataRow["stamp"].GetType() != typeof(DBNull))
                                        cMain.Objects[ObjIdx].Device[DevIdx].FindedDevice[idx].TimeStamp = Convert.ToDateTime( DbDataRow["stamp"].ToString());

                                    idx++;
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            MessageBox.Show(e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }

                }
            }
                            
        return true;
        }

        //Сохранение струтуры дерева сети в БД
        public static Boolean SaveNetwork(Boolean Reload)
        {
            Int32 i, ProgressCount = 0;
            Boolean Result;

            ProgressCount = GetChangesCount();

            if ((cMain.MainWindow != null) && (ProgressCount > 0))
            {                
                for (i = 0; i < cMain.MainWindow.Controls.Count; i++)
                    cMain.MainWindow.Controls[i].Enabled = false;
                ProgressForm = new fProgress();
                ProgressForm.Text = "Сохранение...";
                ProgressForm.InProgress = true;
                ProgressForm.pbProgress.Maximum = ProgressCount;
                ProgressForm.pbProgress.Value = 0;
                ProgressForm.Show(cMain.MainWindow);                
            }
            
            if (ProgressForm != null)
            {
                ProgressForm.lbProgress.Text = "Удаление записей из базы данных";
                Application.DoEvents();
            }
            //Удаление структур
            Result = DeleteFromDB();

            if (ProgressForm != null)
            {
                ProgressForm.lbProgress.Text = "Добавление новых записей в базу данных";
                Application.DoEvents();
            }
            //Добавление типов устройств для справочника
            if (Result) Result = InsertNewDeviceTypes();
            //Добавление типов счетчиков для справочника
            if (Result) Result = InsertNewMeters();
            //Добавление каналов связи для справочника
            if (Result) Result = InsertNewCommChan();
            //Добавление тарифов для справочника
            if (Result) Result = InsertNewTariff();
            //Добавление gльзователей для справочника
            if (Result) Result = InsertNewUsers();
            //Добавление территориальных объединений
            if (Result) Result = InsertNewDC();
            //Добавление объектов учета
            if (Result)
            {
                Result = InsertNewObjects();
            }
            //Добавление устройств для объектов учета
            if (Result) Result = InsertNewDevices();
            //Добавление коммутационного оборудования для устройств 
            if (Result) Result = InsertNewСommEqupment();
            //Добавление присоединений для устройств
            if (Result) Result = InsertNewJoin();
            //Добавление каналов учета для присоединений
            if (Result) Result = InsertNewChannels();
            //Добавление линий электропередач для присоединений
            if (Result) Result = InsertNewConnectionLines();
            //Добавление групп отчетов для присоединений
            if (Result) Result = InsertNewReportGroups();

            if (ProgressForm != null)
            {
                ProgressForm.lbProgress.Text = "Обновление записей в базе данных";
                Application.DoEvents();
            }
            //Обновление в БД справочника типов устройств
            if (Result) Result = UpdateDeviceTypeList();
            //Обновление в БД справочника счетчиков
            if (Result) Result = UpdateMeterList();
            //Обновление в БД справочника каналов связи
            if (Result) Result = UpdateCommChanList();
            //Обновление в БД справочника тарифов
            if (Result) Result = UpdateTariffList();
            //Обновление в БД справочника пользователей
            if (Result) Result = UpdateUserList();
            //Обновление в БД территориальных объединений
            if (Result) Result = UpdateDC();
            //Обновление в БД объектов учета
            if (Result) Result = UpdateObjects();
            //Обновление в БД устройств для объектов учета
            if (Result) Result = UpdateObjectDevices();
            //Обновление в БД коммутационного оборудования для устройств
            if (Result) Result = UpdateDeviceСommEqupment();
            //Обновление в БД присоединений для устройств
            if (Result) Result = UpdateDeviceJoin();
            //Обновление в БД каналов учета для присоединений
            if (Result) Result = UpdateJoinChannels();
            //Обновление в БД линий электропередач для присоединений
            if (Result) Result = UpdateJoinConnectionLines();
            //Обновление в БД групп отчетов для присоединений
            if (Result) Result = UpdateJoinReportGroups();
            
            if ((cMain.MainWindow != null) && (ProgressForm != null))
            {
                for (i = 0; i < cMain.MainWindow.Controls.Count; i++)
                    cMain.MainWindow.Controls[i].Enabled = true;
                ProgressForm.InProgress = false;
                ProgressForm.Close();
                ProgressForm.Dispose();
                ProgressForm = null;
            }
            //Перезагрузка всех параметров из БД
            if ((ProgressCount > 0) && (Reload)) Result = RefreshNetwork();

            return Result;
        }

        //Вычисление общего количества изменений для внесения в БД
        public static Int32 GetChangesCount()
        {
            return GetDeleteProgressCount() + GetInsertProgressCount() + GetUpdateProgressCount();
        }
        //Вычисление количества операция для удаления параметров из БД
        private static Int32 GetDeleteProgressCount()
        {
            Int32 Result = 0;
            Int32 i, j, k, l;

            //Удаление из справочника устройств
            for (i = 0; i < cMain.DevTypeList.Length; i++)
            {
                if ((cMain.DevTypeList[i].ItemAction.DBExist) &&
                    (cMain.DevTypeList[i].ItemAction.Deleted)) Result++;
                    
            }                    
            //Удаление из справочника каналов связи 
            for (i = 0; i < cMain.CommChanList.Length; i++)
            {
                if ((cMain.CommChanList[i].ItemAction.DBExist) &&
                    (cMain.CommChanList[i].ItemAction.Deleted)) Result++;
            }
            //Удаление из справочника счетчиков 
            for (i = 0; i < cMain.MeterList.Length; i++)
            {
                if ((cMain.MeterList[i].ItemAction.DBExist) &&
                    (cMain.MeterList[i].ItemAction.Deleted)) Result++;
            }
            //Удаление из справочника тарифов
            for (i = 0; i < cMain.TariffList.Length; i++)
            {
                if ((cMain.TariffList[i].ItemAction.DBExist) &&
                    (cMain.TariffList[i].ItemAction.Deleted)) Result++;
            }
            //Удаление из справочника пользователей
            for (i = 0; i < cMain.UserList.Length; i++)
            {
                if ((cMain.UserList[i].ItemAction.DBExist) &&
                    (cMain.UserList[i].ItemAction.Deleted)) Result++;
            }
            //Удаление объектов учета
            for (i = 0; i < cMain.Objects.Length; i++)
            {
                if ((cMain.Objects[i].ItemAction.DBExist) && 
                    (cMain.Objects[i].ItemAction.Deleted)) Result++;
                else
                {
                    //Удаление устройств
                    for (j = 0; j < cMain.Objects[i].Device.Length; j++)
                    {
                        if ((cMain.Objects[i].Device[j].ItemAction.DBExist) && 
                            (cMain.Objects[i].Device[j].ItemAction.Deleted)) Result++;
                        else
                        {
                            //Удаление коммутационного оборудования устройства
                            for (k = 0; k < cMain.Objects[i].Device[j].CommEquipment.Length; k++)
                            {
                                if ((cMain.Objects[i].Device[j].CommEquipment[k].ItemAction.DBExist) &&
                                    (cMain.Objects[i].Device[j].CommEquipment[k].ItemAction.Deleted)) Result++;
                            }
                            //Удаление присоединений устройства
                            for (k = 0; k < cMain.Objects[i].Device[j].Join.Length; k++)
                            {
                                if ((cMain.Objects[i].Device[j].Join[k].ItemAction.DBExist) && 
                                    (cMain.Objects[i].Device[j].Join[k].ItemAction.Deleted)) Result++;
                                else
                                {
                                    //Удаление каналов учета присоединения
                                    for (l = 0; l < cMain.Objects[i].Device[j].Join[k].Channel.Length; l++)
                                    {
                                        if ((cMain.Objects[i].Device[j].Join[k].Channel[l].ItemAction.DBExist) && 
                                            (cMain.Objects[i].Device[j].Join[k].Channel[l].ItemAction.Deleted)) Result++;
                                    }
                                    //Удаление линий электропередач присоединения
                                    for (l = 0; l < cMain.Objects[i].Device[j].Join[k].ConnLineLosts.Length; l++)
                                    {
                                        if ((cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ItemAction.DBExist) &&
                                            (cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ItemAction.Deleted)) Result++;
                                    }
                                    //Удаление групп отчетов присоединения
                                    for (l = 0; l < cMain.Objects[i].Device[j].Join[k].ReportGroup.Length; l++)
                                    {
                                        if ((cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ItemAction.DBExist) &&
                                            (cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ItemAction.Deleted)) Result++;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            //Удаление территориальных объединений
            for (i = 0; i < cMain.DC.Length; i++)
            {
                if ((cMain.DC[i].ItemAction.DBExist) &&
                    (cMain.DC[i].ItemAction.Deleted))                        
                    Result++;                        
            }

            return Result;
        }
        //Вычисление количества операция для добавления новых параметров в БД
        private static Int32 GetInsertProgressCount()
        {
            Int32 i, j, k, l;
            Int32 Result = 0;

            //Добавление типов устройств для справочника                                        
            for (i = 0; i < cMain.DevTypeList.Length; i++)
            {
                if ((!cMain.DevTypeList[i].ItemAction.DBExist) &&
                    (!cMain.DevTypeList[i].ItemAction.Deleted)) Result++;
            }
            //Добавление типов счетчиков для справочника
            for (i = 0; i < cMain.MeterList.Length; i++)
            {
                if ((!cMain.MeterList[i].ItemAction.DBExist) &&
                    (!cMain.MeterList[i].ItemAction.Deleted)) Result++;
            }
            for (i = 0; i < cMain.CommChanList.Length; i++)
            {
                if ((!cMain.CommChanList[i].ItemAction.DBExist) &&
                    (!cMain.CommChanList[i].ItemAction.Deleted)) Result++;
            }
            //Добавление тарифов для справочника
            for (i = 0; i < cMain.TariffList.Length; i++)
            {
                if ((!cMain.TariffList[i].ItemAction.DBExist) &&
                    (!cMain.TariffList[i].ItemAction.Deleted)) Result++;
            }
            //Добавление пользователей для справочника
            for (i = 0; i < cMain.UserList.Length; i++)
            {
                if ((!cMain.UserList[i].ItemAction.DBExist) &&
                    (!cMain.UserList[i].ItemAction.Deleted)) Result++;
            }  
            //Добавление территориальных объединений
            for (i = 0; i < cMain.DC.Length; i++)
            {
                if ((!cMain.DC[i].ItemAction.DBExist) &&
                    (!cMain.DC[i].ItemAction.Deleted)) Result++;
            }
            //Добавление структуры
            for (i = 0; i < cMain.Objects.Length; i++)
            {
                if ((!cMain.Objects[i].ItemAction.DBExist) &&
                    (!cMain.Objects[i].ItemAction.Deleted)) Result++;
                if (!cMain.Objects[i].ItemAction.Deleted)
                {
                    for (j = 0; j < cMain.Objects[i].Device.Length; j++)
                    {
                        if ((!cMain.Objects[i].Device[j].ItemAction.DBExist) &&
                            (!cMain.Objects[i].Device[j].ItemAction.Deleted)) Result++;
                        if (!cMain.Objects[i].Device[j].ItemAction.Deleted)
                        {
                            for (k = 0; k < cMain.Objects[i].Device[j].CommEquipment.Length; k++)
                            {
                                if ((!cMain.Objects[i].Device[j].CommEquipment[k].ItemAction.DBExist) &&
                                    (!cMain.Objects[i].Device[j].CommEquipment[k].ItemAction.Deleted)) Result++;
                            }
                            for (k = 0; k < cMain.Objects[i].Device[j].Join.Length; k++)
                            {
                                if ((!cMain.Objects[i].Device[j].Join[k].ItemAction.DBExist) &&
                                    (!cMain.Objects[i].Device[j].Join[k].ItemAction.Deleted)) Result++;
                                if (!cMain.Objects[i].Device[j].Join[k].ItemAction.Deleted)
                                {
                                    for (l = 0; l < cMain.Objects[i].Device[j].Join[k].Channel.Length; l++)
                                    {
                                        if ((!cMain.Objects[i].Device[j].Join[k].Channel[l].ItemAction.DBExist) &&
                                            (!cMain.Objects[i].Device[j].Join[k].Channel[l].ItemAction.Deleted)) Result++;
                                    }
                                    for (l = 0; l < cMain.Objects[i].Device[j].Join[k].ConnLineLosts.Length; l++)
                                    {
                                        if ((!cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ItemAction.DBExist) &&
                                            (!cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ItemAction.Deleted)) Result++;
                                    }
                                    for (l = 0; l < cMain.Objects[i].Device[j].Join[k].ReportGroup.Length; l++)
                                    {
                                        if ((!cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ItemAction.DBExist) &&
                                            (!cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ItemAction.Deleted)) Result++;
                                    }
                                }
                            }
                        }
                    }
                }
            }             

            return Result;
        }
        //Вычисление количества операция для обновления параметров в БД
        private static Int32 GetUpdateProgressCount()
        {
            Int32 i, j, k, l;
            Int32 Result = 0;

            //Обновление типов устройств для справочника                                        
            for (i = 0; i < cMain.DevTypeList.Length; i++)
            {
                if ((cMain.DevTypeList[i].ItemAction.Changed) &&
                    (!cMain.DevTypeList[i].ItemAction.Deleted)) Result++;
            }
            //Обновление типов счетчиков для справочника
            for (i = 0; i < cMain.MeterList.Length; i++)
            {
                if ((cMain.MeterList[i].ItemAction.Changed) &&
                    (!cMain.MeterList[i].ItemAction.Deleted)) Result++;
            }
            //Обновление каналов связи для справочника
            for (i = 0; i < cMain.CommChanList.Length; i++)
            {
                if ((cMain.CommChanList[i].ItemAction.Changed) &&
                    (!cMain.CommChanList[i].ItemAction.Deleted)) Result++;
            }
            //Обновление тарифов для справочника
            for (i = 0; i < cMain.TariffList.Length; i++)
            {
                if ((cMain.TariffList[i].ItemAction.Changed) &&
                    (!cMain.TariffList[i].ItemAction.Deleted)) Result++;
            }
            //Обновление пользователей для справочника
            for (i = 0; i < cMain.UserList.Length; i++)
            {
                if ((cMain.UserList[i].ItemAction.Changed) &&
                    (!cMain.UserList[i].ItemAction.Deleted)) Result++;
            }
            //Обновление территориальных объединений
            for (i = 0; i < cMain.DC.Length; i++)
            {
                if ((cMain.DC[i].ItemAction.Changed) &&
                    (!cMain.DC[i].ItemAction.Deleted)) Result++;
            }
            //Обновление структуры
            for (i = 0; i < cMain.Objects.Length; i++)
            {
                if ((cMain.Objects[i].ItemAction.Changed) &&
                    (!cMain.Objects[i].ItemAction.Deleted)) Result++;
                if (!cMain.Objects[i].ItemAction.Deleted)
                {
                    for (j = 0; j < cMain.Objects[i].Device.Length; j++)
                    {
                        if ((cMain.Objects[i].Device[j].ItemAction.Changed) &&
                            (!cMain.Objects[i].Device[j].ItemAction.Deleted)) Result++;
                        if (!cMain.Objects[i].Device[j].ItemAction.Deleted)
                        {
                            for (k = 0; k < cMain.Objects[i].Device[j].CommEquipment.Length; k++)
                            {
                                if ((cMain.Objects[i].Device[j].CommEquipment[k].ItemAction.Changed) &&
                                    (!cMain.Objects[i].Device[j].CommEquipment[k].ItemAction.Deleted)) Result++;
                            }
                            for (k = 0; k < cMain.Objects[i].Device[j].Join.Length; k++)
                            {
                                if ((cMain.Objects[i].Device[j].Join[k].ItemAction.Changed) &&
                                    (!cMain.Objects[i].Device[j].Join[k].ItemAction.Deleted)) Result++;
                                if (!cMain.Objects[i].Device[j].Join[k].ItemAction.Deleted)
                                {
                                    for (l = 0; l < cMain.Objects[i].Device[j].Join[k].Channel.Length; l++)
                                    {
                                        if ((cMain.Objects[i].Device[j].Join[k].Channel[l].ItemAction.Changed) &&
                                            (!cMain.Objects[i].Device[j].Join[k].Channel[l].ItemAction.Deleted)) Result++;
                                    }
                                    for (l = 0; l < cMain.Objects[i].Device[j].Join[k].ConnLineLosts.Length; l++)
                                    {
                                        if ((cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ItemAction.Changed) &&
                                            (!cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ItemAction.Deleted)) Result++;
                                    }
                                    for (l = 0; l < cMain.Objects[i].Device[j].Join[k].ReportGroup.Length; l++)
                                    {
                                        if ((cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ItemAction.Changed) &&
                                            (!cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ItemAction.Deleted)) Result++;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return Result;
        }

        //Удаление из базы отмеченных структур
        private static Boolean DeleteFromDB()
        { 
            OleDbCommand DbCommand = null;
            Boolean Result = true;
            Int32 i, j, k, l;        

            if (DbConnect != null)
            {                
                try
                {
                    DbCommand = DbConnect.CreateCommand();

                    //Удаление из справочника типов устройств 
                    for (i = 0; i < cMain.DevTypeList.Length; i++)
                    {
                        if ((cMain.DevTypeList[i].ItemAction.DBExist) && 
                            (cMain.DevTypeList[i].ItemAction.Deleted))
                        {
                            DbCommand.CommandText = "delete from DEVREF where DEVID=" + cMain.DevTypeList[i].ID.ToString();
                            if (DbCommand.ExecuteNonQuery() > 0)
                                cMain.DevTypeList[i].ItemAction.DBExist = false;
                            AddToProgress(1);
                        }
                    }                    
                    //Удаление из справочника каналов связи 
                    for (i = 0; i < cMain.CommChanList.Length; i++)
                    {
                        if ((cMain.CommChanList[i].ItemAction.DBExist) && 
                            (cMain.CommChanList[i].ItemAction.Deleted))
                        {
                            DbCommand.CommandText = "delete from COMCHAN where CHANID=" + cMain.CommChanList[i].ID.ToString();
                            if (DbCommand.ExecuteNonQuery() > 0)
                                cMain.CommChanList[i].ItemAction.DBExist = false;
                            AddToProgress(1);
                        }
                    }
                    //Удаление из справочника счетчиков 
                    for (i = 0; i < cMain.MeterList.Length; i++)
                    {
                        if ((cMain.MeterList[i].ItemAction.DBExist) && 
                            (cMain.MeterList[i].ItemAction.Deleted))
                        {                            
                            DbCommand.CommandText = "delete from METERS where METER=" + cMain.MeterList[i].ID.ToString();
                            if (DbCommand.ExecuteNonQuery() > 0)
                                cMain.MeterList[i].ItemAction.DBExist = false;
                            AddToProgress(1);
                        }
                    }
                    //Удаление из справочника тарифов
                    for (i = 0; i < cMain.TariffList.Length; i++)
                    {
                        if ((cMain.TariffList[i].ItemAction.DBExist) && 
                            (cMain.TariffList[i].ItemAction.Deleted))
                        {
                            DbCommand.CommandText = "delete from TARIFF where IDTF=" + cMain.TariffList[i].ID.ToString();
                            if (DbCommand.ExecuteNonQuery() > 0)
                                cMain.TariffList[i].ItemAction.DBExist = false;
                            AddToProgress(1);
                        }
                    }
                    //Удаление из справочника пользователей
                    for (i = 0; i < cMain.UserList.Length; i++)
                    {
                        if ((cMain.UserList[i].ItemAction.DBExist) &&
                            (cMain.UserList[i].ItemAction.Deleted))
                        {
                            DbCommand.CommandText = "delete from TELECONTROL_USERS where TCUSERID=" + cMain.UserList[i].ID.ToString();
                            if (DbCommand.ExecuteNonQuery() > 0)
                                cMain.UserList[i].ItemAction.DBExist = false;
                            AddToProgress(1);
                        }
                    }

                    //Удаление объектов учета
                    for (i = 0; i < cMain.Objects.Length; i++)
                    {
                        if ((cMain.Objects[i].ItemAction.DBExist) && 
                            (cMain.Objects[i].ItemAction.Deleted))
                        {
                            DbCommand.CommandText = "delete from DSROBJ where DCID=" + cMain.Objects[i].DCID.ToString() + " and OBJID=" + cMain.Objects[i].ID.ToString();
                            if (DbCommand.ExecuteNonQuery() > 0)
                            {
                                cMain.Objects[i].ItemAction.DBExist = false;
                                for (j = 0; j < cMain.Objects[i].Device.Length; j++)
                                {
                                    cMain.Objects[i].Device[j].ItemAction.DBExist = false;
                                    for (k = 0; k < cMain.Objects[i].Device[j].Join.Length; k++)
                                    {
                                        cMain.Objects[i].Device[j].Join[k].ItemAction.DBExist = false;
                                        for (l = 0; l < cMain.Objects[i].Device[j].Join[k].Channel.Length; l++)
                                            cMain.Objects[i].Device[j].Join[k].Channel[l].ItemAction.DBExist = false;
                                        for (l = 0; l < cMain.Objects[i].Device[j].Join[k].ConnLineLosts.Length; l++)
                                            cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ItemAction.DBExist = false;
                                        for (l = 0; l < cMain.Objects[i].Device[j].Join[k].ReportGroup.Length; l++)
                                            cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ItemAction.DBExist = false;
                                    }
                                }
                            }
                            AddToProgress(1);
                        }
                        else
                        {
                            //Удаление устройств
                            for (j = 0; j < cMain.Objects[i].Device.Length; j++)
                            {
                                if ((cMain.Objects[i].Device[j].ItemAction.DBExist) && 
                                    (cMain.Objects[i].Device[j].ItemAction.Deleted))
                                {
                                    DbCommand.CommandText = "delete from DEVICES where DCID=" + cMain.Objects[i].DCID.ToString() + " and OBJID=" + cMain.Objects[i].ID.ToString() + " and DEVINC=" + cMain.Objects[i].Device[j].ID.ToString();
                                    if (DbCommand.ExecuteNonQuery() > 0)
                                    {
                                        cMain.Objects[i].Device[j].ItemAction.DBExist = false;
                                        for (k = 0; k < cMain.Objects[i].Device[j].CommEquipment.Length; k++)
                                            cMain.Objects[i].Device[j].CommEquipment[k].ItemAction.DBExist = false;                                        
                                        for (k = 0; k < cMain.Objects[i].Device[j].Join.Length; k++)
                                        {
                                            cMain.Objects[i].Device[j].Join[k].ItemAction.DBExist = false;
                                            for (l = 0; l < cMain.Objects[i].Device[j].Join[k].Channel.Length; l++)
                                                cMain.Objects[i].Device[j].Join[k].Channel[l].ItemAction.DBExist = false;
                                            for (l = 0; l < cMain.Objects[i].Device[j].Join[k].ConnLineLosts.Length; l++)
                                                cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ItemAction.DBExist = false;
                                            for (l = 0; l < cMain.Objects[i].Device[j].Join[k].ReportGroup.Length; l++)
                                                cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ItemAction.DBExist = false;
                                        }
                                    }
                                    AddToProgress(1);
                                }
                                else
                                {
                                    //Удаление коммутационного оборудования устройства
                                    for (k = 0; k < cMain.Objects[i].Device[j].CommEquipment.Length; k++)
                                    {
                                        if ((cMain.Objects[i].Device[j].CommEquipment[k].ItemAction.DBExist) &&
                                            (cMain.Objects[i].Device[j].CommEquipment[k].ItemAction.Deleted))
                                        {
                                            DbCommand.CommandText = "delete from IDC_STATE where DCID=" + cMain.Objects[i].DCID.ToString() + " and OBJID=" + cMain.Objects[i].ID.ToString() + " and DEVINC=" + cMain.Objects[i].Device[j].ID.ToString();
                                            if (DbCommand.ExecuteNonQuery() > 0)
                                                cMain.Objects[i].Device[j].CommEquipment[k].ItemAction.DBExist = false;
                                            AddToProgress(1);
                                        }
                                    }
                                    //Удаление присоединений устройства
                                    for (k = 0; k < cMain.Objects[i].Device[j].Join.Length; k++)
                                    {
                                        if ((cMain.Objects[i].Device[j].Join[k].ItemAction.DBExist) && 
                                            (cMain.Objects[i].Device[j].Join[k].ItemAction.Deleted))
                                        {
                                            DbCommand.CommandText = "delete from JOINS where DCID=" + cMain.Objects[i].DCID.ToString() + " and OBJID=" + cMain.Objects[i].ID.ToString() + " and DEVINC=" + cMain.Objects[i].Device[j].ID.ToString() + " and JOINID=" + cMain.Objects[i].Device[j].Join[k].ID.ToString();
                                            if (DbCommand.ExecuteNonQuery() > 0)
                                            {
                                                cMain.Objects[i].Device[j].Join[k].ItemAction.DBExist = false;
                                                for (l = 0; l < cMain.Objects[i].Device[j].Join[k].Channel.Length; l++)
                                                    cMain.Objects[i].Device[j].Join[k].Channel[l].ItemAction.DBExist = false;
                                                for (l = 0; l < cMain.Objects[i].Device[j].Join[k].ConnLineLosts.Length; l++)
                                                    cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ItemAction.DBExist = false;
                                                for (l = 0; l < cMain.Objects[i].Device[j].Join[k].ReportGroup.Length; l++)
                                                    cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ItemAction.DBExist = false; 
                                            }
                                            AddToProgress(1);
                                        }
                                        else
                                        {
                                            //Удаление каналов учета присоединения
                                            for (l = 0; l < cMain.Objects[i].Device[j].Join[k].Channel.Length; l++)
                                            {
                                                if ((cMain.Objects[i].Device[j].Join[k].Channel[l].ItemAction.DBExist) && 
                                                    (cMain.Objects[i].Device[j].Join[k].Channel[l].ItemAction.Deleted))
                                                {
                                                    DbCommand.CommandText = "delete from CHANNELS where DCID=" + cMain.Objects[i].DCID.ToString() + " and OBJID=" + cMain.Objects[i].ID.ToString() + " and DEVID=" + cMain.Objects[i].Device[j].Join[k].DeviceID.ToString() + " and JOINID=" + cMain.Objects[i].Device[j].Join[k].ID.ToString() + " and CHANID=" + cMain.Objects[i].Device[j].Join[k].Channel[l].ID.ToString();
                                                    if (DbCommand.ExecuteNonQuery() > 0)
                                                        cMain.Objects[i].Device[j].Join[k].Channel[l].ItemAction.DBExist = false;
                                                    AddToProgress(1);
                                                }
                                            }
                                            //Удаление линий электропередач присоединения
                                            for (l = 0; l < cMain.Objects[i].Device[j].Join[k].ConnLineLosts.Length; l++)
                                            {
                                                if ((cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ItemAction.DBExist) &&
                                                    (cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ItemAction.Deleted))
                                                {
                                                    DbCommand.CommandText = "delete from LINES where JOININC=" + cMain.Objects[i].Device[j].Join[k].Index.ToString() + " and LINEID=" + cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ID.ToString();                                                    
                                                    if (DbCommand.ExecuteNonQuery() > 0)                                                    
                                                        cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ItemAction.DBExist = false;
                                                    AddToProgress(1);
                                                }
                                            }
                                            //Удаление групп отчетов присоединения
                                            for (l = 0; l < cMain.Objects[i].Device[j].Join[k].ReportGroup.Length; l++)
                                            {
                                                if ((cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ItemAction.DBExist) &&
                                                    (cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ItemAction.Deleted))
                                                {                                                    
                                                    DbCommand.CommandText = "delete from JOIN_GROUP where DCID=" + cMain.Objects[i].DCID.ToString() + " and OBJID=" + cMain.Objects[i].ID.ToString() + " and DEVID=" + cMain.Objects[i].Device[j].Join[k].DeviceID.ToString() + " and JOINID=" + cMain.Objects[i].Device[j].Join[k].ID.ToString() + " and REPGROUPID=" + cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ID.ToString();                                                    
                                                    if (DbCommand.ExecuteNonQuery() > 0)
                                                        cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ItemAction.DBExist = false;
                                                    AddToProgress(1);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    //Удаление территориальных объединений
                    for (i = 0; i < cMain.DC.Length; i++)
                    {
                        if ((cMain.DC[i].ItemAction.DBExist) &&
                            (cMain.DC[i].ItemAction.Deleted))
                        {
                            DbCommand.CommandText = "delete from DC where ID=" + cMain.DC[i].ID.ToString();
                            if (DbCommand.ExecuteNonQuery() > 0)
                                cMain.DC[i].ItemAction.DBExist = false;
                            AddToProgress(1);
                        }
                    }
                }
                catch (Exception e)
                {
                    Result = false;
                    MessageBox.Show(DbCommand.CommandText + e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);                    
                }                
            }
            return Result;
        }
                
        //Добавление в справочник БД новых типов устройств
        public static Boolean InsertNewDeviceTypes()
        {
            OleDbCommand DbCommand = null;
            Boolean Result = true;
            Int32 i;

            if (DbConnect != null)
            {
                try
                {
                    DbCommand = DbConnect.CreateCommand();
                    //Добавление типов устройств для справочника                                        
                    for (i = 0; i < cMain.DevTypeList.Length; i++)
                    {
                        if ((!cMain.DevTypeList[i].ItemAction.DBExist) &&
                            (!cMain.DevTypeList[i].ItemAction.Deleted))
                        {
                            DbCommand.CommandText =
                                "insert into DEVREF(DEVID,TITLE,DEVTYPE,DRIVER,CHANNELS,DEVICENAME,PROTOCOLNAME,FILECODESNPATS,SETTINGS) values(" +
                                FixIdentifierName(cMain.DevTypeList[i].ID.ToString()) + "," +
                                "'" + FixIdentifierName(cMain.DevTypeList[i].Caption) + "'" + "," +
                                FixIdentifierName(cMain.DevTypeList[i].DeviceKind.ToString()) + "," +
                                "''" + "," +
                                FixIdentifierName(cMain.DevTypeList[i].ChannelCount.ToString()) + "," +
                                "'" + FixIdentifierName(cMain.DevTypeList[i].DeviceDllName) + "'" + "," +
                                "'" + FixIdentifierName(cMain.DevTypeList[i].ProtocolDLLName) + "'" + "," +
                                "'" + FixIdentifierName(cMain.DevTypeList[i].FileCodeNPATS) + "'" + "," +
                                "?)";
                            DbCommand.Parameters.Clear();
                            DbCommand.Parameters.Add("@SETTINGS", OleDbType.LongVarBinary, cMain.DevTypeList[i].ProtocolSetting.Length, "SETTINGS").Value = cMain.DevTypeList[i].ProtocolSetting;
                            if (DbCommand.ExecuteNonQuery() > 0)
                            {
                                cMain.DevTypeList[i].ItemAction.DBExist = true;
                                cMain.DevTypeList[i].ItemAction.Changed = false;
                            }
                            AddToProgress(1);
                        }
                    }
                }
                catch (Exception e)
                {
                    Result = false;
                    MessageBox.Show(DbCommand.CommandText + e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return Result;     
        }
        //Добавление в справочник БД новых счетчиков
        public static Boolean InsertNewMeters()
        {
            OleDbCommand DbCommand = null;
            Boolean Result = true;
            Int32 i;

            if (DbConnect != null)
            {
                try
                {
                    DbCommand = DbConnect.CreateCommand();
                    //Добавление типов счетчиков для справочника
                    for (i = 0; i < cMain.MeterList.Length; i++)
                    {
                        if ((!cMain.MeterList[i].ItemAction.DBExist) &&
                            (!cMain.MeterList[i].ItemAction.Deleted))
                        {
                            DbCommand.CommandText =
                                "insert into METERS(METER,TITLE,PREC,INTDIGITS,DECIMALDIGITS,KOEFF,PHASETYPE,SELFUSE) values(" +
                                FixIdentifierName(cMain.MeterList[i].ID.ToString()) + "," +
                                "'" + FixIdentifierName(cMain.MeterList[i].Caption) + "'" + "," +
                                FixIdentifierName(cMain.MeterList[i].Precision.ToString().Replace(",", ".")) + "," +
                                FixIdentifierName(cMain.MeterList[i].BeforeComma.ToString()) + "," +
                                FixIdentifierName(cMain.MeterList[i].AfterComma.ToString()) + "," +
                                FixIdentifierName(cMain.MeterList[i].MeterConst.ToString()) + "," +
                                FixIdentifierName(cMain.MeterList[i].Phase.ToString()) + "," +
                                FixIdentifierName(cMain.MeterList[i].SelfDemand.ToString().Replace(",", ".")) + ")";
                            if (DbCommand.ExecuteNonQuery() > 0)
                            {
                                cMain.MeterList[i].ItemAction.DBExist = true;
                                cMain.MeterList[i].ItemAction.Changed = false;
                            }
                            AddToProgress(1);
                        }
                    }
                }
                catch (Exception e)
                {
                    Result = false;
                    MessageBox.Show(DbCommand.CommandText + e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return Result;
        }
        //Добавление в справочник БД новых каналов связи
        public static Boolean InsertNewCommChan()
        {
            OleDbCommand DbCommand = null;
            Boolean Result = true;
            Int32 i;

            if (DbConnect != null)
            {
                try
                {
                    DbCommand = DbConnect.CreateCommand();                    
                    //Добавление каналов связи для справочника
                    for (i = 0; i < cMain.CommChanList.Length; i++)
                    {
                        if ((!cMain.CommChanList[i].ItemAction.DBExist) &&
                            (!cMain.CommChanList[i].ItemAction.Deleted))
                        {
                            DbCommand.CommandText =
                                "insert into COMCHAN(CHANID,COMNAME,NAME,PORT,SETTING) values(" +
                                FixIdentifierName(cMain.CommChanList[i].ID.ToString()) + "," +
                                "'" + FixIdentifierName(cMain.CommChanList[i].DllName) + "'" + "," +
                                "'" + FixIdentifierName(cMain.CommChanList[i].Caption) + "'" + "," +
                                FixIdentifierName(cMain.CommChanList[i].GroupID.ToString()) + "," +
                                "?)";
                            DbCommand.Parameters.Clear();
                            DbCommand.Parameters.Add("@SETTING", OleDbType.LongVarBinary, cMain.CommChanList[i].Setting.Length, "SETTING").Value = cMain.CommChanList[i].Setting;
                            if (DbCommand.ExecuteNonQuery() > 0)
                            {
                                cMain.CommChanList[i].ItemAction.DBExist = true;
                                cMain.CommChanList[i].ItemAction.Changed = false;
                            }
                            AddToProgress(1);
                        }
                    }
                }
                catch (Exception e)
                {
                    Result = false;
                    MessageBox.Show(DbCommand.CommandText + e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return Result;
        }
        //Добавление в справочник БД новых тарифов
        public static Boolean InsertNewTariff()
        {
            OleDbCommand DbCommand = null;
            Boolean Result = true;
            Int32 i;

            if (DbConnect != null)
            {
                try
                {
                    DbCommand = DbConnect.CreateCommand();
                    //Добавление тарифов для справочника
                    for (i = 0; i < cMain.TariffList.Length; i++)
                    {
                        if ((!cMain.TariffList[i].ItemAction.DBExist) &&
                            (!cMain.TariffList[i].ItemAction.Deleted))
                        {
                            DbCommand.CommandText =
                                "insert into TARIFF(IDTF,NM,COLOR) values(" +
                                FixIdentifierName(cMain.TariffList[i].ID.ToString()) + "," +
                                "'" + FixIdentifierName(cMain.TariffList[i].Caption) + "'" + "," +
                                FixIdentifierName(cMain.TariffList[i].FillColor.ToString()) + ")";
                            if (DbCommand.ExecuteNonQuery() > 0)
                            {
                                cMain.TariffList[i].ItemAction.DBExist = true;
                                cMain.TariffList[i].ItemAction.Changed = false;
                            }
                            AddToProgress(1);
                        }
                    }
                }
                catch (Exception e)
                {
                    Result = false;
                    MessageBox.Show(DbCommand.CommandText + e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return Result;
        }
        //Добавление в справочник БД новых пользователей
        public static Boolean InsertNewUsers()
        {
            OleDbCommand DbCommand = null;
            Boolean Result = true;
            Int32 i;

            if (DbConnect != null)
            {
                try
                {
                    DbCommand = DbConnect.CreateCommand();
                    //Добавление пользователей для справочника
                    for (i = 0; i < cMain.UserList.Length; i++)
                    {
                        if ((!cMain.UserList[i].ItemAction.DBExist) &&
                            (!cMain.UserList[i].ItemAction.Deleted))
                        {
                            DbCommand.CommandText =
                                "insert into TELECONTROL_USERS(TCUSERID,TCUSER,TCPASSWORD,TCURID) values(" +
                                FixIdentifierName(cMain.UserList[i].ID.ToString()) + "," +
                                "'" + FixIdentifierName(cMain.UserList[i].Caption) + "'" + "," +
                                "'" + FixIdentifierName(cMain.UserList[i].Password) + "'" + "," +
                                FixIdentifierName(cMain.UserList[i].AccessID.ToString()) + ")";
                            if (DbCommand.ExecuteNonQuery() > 0)
                            {
                                cMain.UserList[i].ItemAction.DBExist = true;
                                cMain.UserList[i].ItemAction.Changed = false;
                            }
                            AddToProgress(1);
                        }
                    }
                }
                catch (Exception e)
                {
                    Result = false;
                    MessageBox.Show(DbCommand.CommandText + e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return Result;
        }
        //Добавление в БД новых территориальных объединений
        public static Boolean InsertNewDC()
        {
            OleDbCommand DbCommand = null;
            Boolean Result = true;
            Int32 i;

            if (DbConnect != null)
            {
                try
                {
                    DbCommand = DbConnect.CreateCommand();            
                    //Добавление территориальных объединений
                    for (i = 0; i < cMain.DC.Length; i++)
                    {
                        if ((!cMain.DC[i].ItemAction.DBExist) &&
                            (!cMain.DC[i].ItemAction.Deleted))
                        {
                            DbCommand.CommandText =
                                "insert into DC(PARENT,ID,NAME) values(" +
                                FixIdentifierName(cMain.DC[i].ParentID.ToString()) + "," +
                                FixIdentifierName(cMain.DC[i].ID.ToString()) + "," +
                                "'" + FixIdentifierName(cMain.DC[i].Caption) + "'" + ")";
                            if (DbCommand.ExecuteNonQuery() > 0)
                            {
                                cMain.DC[i].ItemAction.DBExist = true;
                                cMain.DC[i].ItemAction.Changed = false;
                            }
                            AddToProgress(1);
                        }
                    }
                }
                catch (Exception e)
                {
                    Result = false;
                    MessageBox.Show(DbCommand.CommandText + e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return Result;
        }
        //Добавление в БД новых объектов учета
        public static Boolean InsertNewObjects()
        {
            OleDbCommand DbCommand = null;
            Boolean Result = true;
            Int32 i, j, Count;
            Byte State1, State2;
            String ObjCommChan, ObjAddCommChan, ExportDCID, ExportObjID;
            Boolean[] ItemChange;
            Boolean NextTime;

            if (DbConnect != null)
            {
                try
                {
                    DbCommand = DbConnect.CreateCommand();            
                    //Добавление объектов учета
                    for (i = 0; i < cMain.Objects.Length; i++)
                    {
                        if ((!cMain.Objects[i].ItemAction.DBExist) &&
                            (!cMain.Objects[i].ItemAction.Deleted))
                        {
                            if (cMain.Objects[i].CollectionState) State1 = 1;
                            else State1 = 0;
                            ExportDCID = "NULL";
                            ExportObjID = "NULL";
                            if (cMain.Objects[i].IsExported)
                            {
                                State2 = 1;
                                if ((cMain.Objects[i].ExportDCID >= 0) && (cMain.Objects[i].ExportObjID >= 0))
                                {
                                    ExportDCID = cMain.Objects[i].ExportDCID.ToString();
                                    ExportObjID = cMain.Objects[i].ExportObjID.ToString();
                                }                                    
                            }
                            else State2 = 0;                            
                            if (cMain.Objects[i].CommChan >= 0) ObjCommChan = cMain.Objects[i].CommChan.ToString();
                            else ObjCommChan = "NULL";
                            if (cMain.Objects[i].AddCommChan >= 0) ObjAddCommChan = cMain.Objects[i].AddCommChan.ToString();
                            else ObjAddCommChan = "NULL";
                            DbCommand.CommandText =
                                "insert into DSROBJ(DCID,OBJID,NAME,GATE,FCHAN,RCHAN,PRIORITY,ISACTIVE,DATESTART,NPATS_ID,KOD63002,EXPORTACTIVE,DCIDEXP,OBJIDEXP,TCPERIODTYPE,TCPERIODCOUNT) values(" +
                                FixIdentifierName(cMain.Objects[i].DCID.ToString()) + "," +
                                FixIdentifierName(cMain.Objects[i].ID.ToString()) + "," +
                                "'" + FixIdentifierName(cMain.Objects[i].Caption) + "'" + "," +
                                FixIdentifierName(cMain.Objects[i].ComputerAddress.ToString()) + "," +
                                ObjCommChan + "," + ObjAddCommChan + "," + "1" + "," +
                                State1.ToString() + "," +
                                "to_date('" + FixIdentifierName(cMain.Objects[i].CollectionStartDT.ToString()) + "','dd.mm.yyyy hh24:mi:ss'), " +
                                "'" + FixIdentifierName(cMain.Objects[i].CodeNPATS) + "'" + "," +
                                "'" + FixIdentifierName(cMain.Objects[i].Code63002) + "'" + "," +
                                State2.ToString() + "," +
                                ExportDCID + "," +
                                ExportObjID + "," +
                                FixIdentifierName(cMain.Objects[i].tcPeriodType.ToString()) + "," +
                                FixIdentifierName(cMain.Objects[i].tcPeriodCount.ToString()) + ")";
                            if (DbCommand.ExecuteNonQuery() > 0)
                            {
                                cMain.Objects[i].ItemAction.DBExist = true;
                                cMain.Objects[i].ItemAction.Changed = false;
                                
                                //Обновление тарифного расписания
                                Count = 0;
                                NextTime = true;
                                ItemChange = new Boolean[cMain.Objects[i].Schedule.Length];
                                for (j = 0; j < ItemChange.Length; j++) ItemChange[j] = false;
                                while ((NextTime) && (Count < ItemChange.Length))
                                {
                                    NextTime = false;
                                    for (j = 0; j < cMain.Objects[i].Schedule.Length; j++)
                                    {
                                        if (!ItemChange[j])
                                        {
                                            if (cMain.Objects[i].Schedule[j].CollectOn) State1 = 1;
                                            else State1 = 0;
                                            DbCommand.CommandText =
                                                "update SCHEDULE set" +
                                                " SACTIVE=" + State1.ToString() + "," +
                                                " PERTYPECOLL=" + FixIdentifierName(cMain.Objects[i].Schedule[j].CPeriodType.ToString()) + "," +
                                                " PERIODCOLL=" + FixIdentifierName(cMain.Objects[i].Schedule[j].CPeriodCount.ToString()) + "," +
                                                " PERTYPEDATA=" + FixIdentifierName(cMain.Objects[i].Schedule[j].DPeriodType.ToString()) + "," +
                                                " PERIODDATA=" + FixIdentifierName(cMain.Objects[i].Schedule[j].DPeriodCount.ToString()) + "," +
                                                " DEPTHTYPECOLLHOLES=" + FixIdentifierName(cMain.Objects[i].Schedule[j].HPeriodType.ToString()) + "," +
                                                " DEPTHCOLLHOLES=" + FixIdentifierName(cMain.Objects[i].Schedule[j].HPeriodCount.ToString()) +
                                                " where DCID=" + FixIdentifierName(cMain.Objects[i].DCID.ToString()) +
                                                " and OBJID=" + FixIdentifierName(cMain.Objects[i].ID.ToString()) +
                                                " and SHEDID=" + FixIdentifierName(cMain.Objects[i].Schedule[j].ID.ToString()) +
                                                " and PERTYPEDATA=" + FixIdentifierName(cMain.Objects[i].Schedule[j].PeriodTypeID.ToString()) +
                                                " and PERIODDATA=" + FixIdentifierName(cMain.Objects[i].Schedule[j].PeriodCountID.ToString());
                                            try
                                            {
                                                if (DbCommand.ExecuteNonQuery() > 0)
                                                {
                                                    ItemChange[j] = true;
                                                    cMain.Objects[i].Schedule[j].PeriodTypeID = cMain.Objects[i].Schedule[j].DPeriodType;
                                                    cMain.Objects[i].Schedule[j].PeriodCountID = cMain.Objects[i].Schedule[j].DPeriodCount;                                                    
                                                }
                                            }
                                            catch { NextTime = true; }
                                        }
                                    }
                                    Count++;
                                }
                            }
                            AddToProgress(1);
                        }
                    }
                }
                catch (Exception e)
                {
                    Result = false;
                    MessageBox.Show(DbCommand.CommandText + e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return Result;
        }
        //Добавление в БД новых устройств для объектов учета
        public static Boolean InsertNewDevices()
        {
            OleDbCommand DbCommand = null;
            Boolean Result = true;
            Int32 i, j;
            Byte State1;

            if (DbConnect != null)
            {
                try
                {
                    DbCommand = DbConnect.CreateCommand();                    
                    //Добавление устройств для объектов учета
                    for (i = 0; i < cMain.Objects.Length; i++)
                    {
                        if ((cMain.Objects[i].ItemAction.DBExist) &&
                            (!cMain.Objects[i].ItemAction.Deleted))
                        {
                            for (j = 0; j < cMain.Objects[i].Device.Length; j++)
                            {
                                if ((!cMain.Objects[i].Device[j].ItemAction.DBExist) &&
                                    (!cMain.Objects[i].Device[j].ItemAction.Deleted))
                                {
                                    if (cMain.Objects[i].Device[j].IsExported)
                                        State1 = 1;
                                    else State1 = 0;
                                    DbCommand.CommandText =
                                        "insert into DEVICES(DCID,OBJID,DEVINC,DEVICE,NET,DEVID,IDENTIFIER,SERNUM,LOGDATEEND,LASTEVENTNUMBER,EXPORTACTIVE,LOGIN,PASS,SETTINGS) values(" +
                                        FixIdentifierName(cMain.Objects[i].DCID.ToString()) + "," +
                                        FixIdentifierName(cMain.Objects[i].ID.ToString()) + "," +
                                        FixIdentifierName(cMain.Objects[i].Device[j].ID.ToString()) + "," +
                                        FixIdentifierName(cMain.Objects[i].Device[j].DeviceID.ToString()) + "," +
                                        FixIdentifierName(cMain.Objects[i].Device[j].NetAddress.ToString()) + "," +
                                        FixIdentifierName(cMain.Objects[i].Device[j].Address.ToString()) + "," +
                                        "'" + FixIdentifierName(cMain.Objects[i].Device[j].Identifier) + "'" + "," +
                                        "'" + FixIdentifierName(cMain.Objects[i].Device[j].SerialNumber) + "'" + "," +
                                        "to_date('" + FixIdentifierName(cMain.Objects[i].Device[j].JournalLastDT.ToString()) + "','dd.mm.yyyy hh24:mi:ss')," +
                                        FixIdentifierName(cMain.Objects[i].Device[j].LastEventIdx.ToString()) + "," +
                                        FixIdentifierName(State1.ToString()) + "," +
                                        "'" + FixIdentifierName(cMain.Objects[i].Device[j].UserName) + "'" + "," +
                                        "'" + FixIdentifierName(cMain.Objects[i].Device[j].UserPassword) + "'" + "," +
                                        "?)";
                                    DbCommand.Parameters.Clear();
                                    if (cMain.Objects[i].Device[j].ProtocolSetting.Length > 0)
                                        DbCommand.Parameters.Add("@SETTINGS", OleDbType.LongVarBinary, cMain.Objects[i].Device[j].ProtocolSetting.Length, "SETTINGS").Value = cMain.Objects[i].Device[j].ProtocolSetting;
                                    else DbCommand.Parameters.Add("@SETTINGS", OleDbType.LongVarBinary, cMain.Objects[i].Device[j].ProtocolSetting.Length, "SETTINGS").Value = null;
                                    if (DbCommand.ExecuteNonQuery() > 0)
                                    {
                                        cMain.Objects[i].Device[j].ItemAction.DBExist = true;
                                        cMain.Objects[i].Device[j].ItemAction.Changed = false;
                                    }
                                    AddToProgress(1);
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Result = false;
                    MessageBox.Show(DbCommand.CommandText + e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return Result;
        }
        //Добавление в БД нового коммутационного оборудования для устройств
        public static Boolean InsertNewСommEqupment()
        {
            OleDbCommand DbCommand = null;
            Boolean Result = true;
            Int32 i, j, k;

            if (DbConnect != null)
            {
                try
                {
                    DbCommand = DbConnect.CreateCommand();
                    //Добавление коммутационного оборудования для устройств
                    for (i = 0; i < cMain.Objects.Length; i++)
                    {
                        if ((cMain.Objects[i].ItemAction.DBExist) &&
                            (!cMain.Objects[i].ItemAction.Deleted))
                        {
                            for (j = 0; j < cMain.Objects[i].Device.Length; j++)
                            {
                                if ((cMain.Objects[i].Device[j].ItemAction.DBExist) &&
                                    (!cMain.Objects[i].Device[j].ItemAction.Deleted))
                                {
                                    for (k = 0; k < cMain.Objects[i].Device[j].CommEquipment.Length; k++)
                                    {
                                        if ((!cMain.Objects[i].Device[j].CommEquipment[k].ItemAction.DBExist) &&
                                            (!cMain.Objects[i].Device[j].CommEquipment[k].ItemAction.Deleted))
                                        {                                            
                                            DbCommand.CommandText =
                                                "insert into IDC_STATE(DCID,OBJID,DEVINC,IDINC,IDSTATE,NAME) values(" +
                                                FixIdentifierName(cMain.Objects[i].DCID.ToString()) + "," +
                                                FixIdentifierName(cMain.Objects[i].ID.ToString()) + "," +
                                                FixIdentifierName(cMain.Objects[i].Device[j].ID.ToString()) + "," +            
                                                FixIdentifierName(cMain.Objects[i].Device[j].CommEquipment[k].ID.ToString()) + "," +
                                                FixIdentifierName(cMain.Objects[i].Device[j].CommEquipment[k].ChannelNumber.ToString()) + "," +
                                                "'" + FixIdentifierName(cMain.Objects[i].Device[j].CommEquipment[k].Caption) + "'" + ")";                                                
                                            if (DbCommand.ExecuteNonQuery() > 0)
                                            {
                                                cMain.Objects[i].Device[j].CommEquipment[k].ItemAction.DBExist = true;
                                                cMain.Objects[i].Device[j].CommEquipment[k].ItemAction.Changed = false;
                                            }
                                            AddToProgress(1);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Result = false;
                    MessageBox.Show(DbCommand.CommandText + e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return Result;
        }
        //Добавление в БД новых присоединений для устройств
        public static Boolean InsertNewJoin()
        {
            OleDbCommand DbCommand = null;
            Boolean Result = true;
            Byte State1, State2, State3, State4;
            Int32 i, j, k;
            DebugLogger ds = new DebugLogger(String.Empty, true);
            if (DbConnect != null)
            {
                try
                {
                    DbCommand = DbConnect.CreateCommand();
                    //Добавление присоединений для устройств
                    for (i = 0; i < cMain.Objects.Length; i++)
                    {
                        if ((cMain.Objects[i].ItemAction.DBExist) &&
                            (!cMain.Objects[i].ItemAction.Deleted))
                        {
                            for (j = 0; j < cMain.Objects[i].Device.Length; j++)
                            {
                                if ((cMain.Objects[i].Device[j].ItemAction.DBExist) &&
                                    (!cMain.Objects[i].Device[j].ItemAction.Deleted))
                                {
                                    for (k = 0; k < cMain.Objects[i].Device[j].Join.Length; k++)
                                    {
                                        if ((!cMain.Objects[i].Device[j].Join[k].ItemAction.DBExist) &&
                                            (!cMain.Objects[i].Device[j].Join[k].ItemAction.Deleted))
                                        {
                                            if (cMain.Objects[i].Device[j].Join[k].CollectEnable) 
                                                State1 = 1;
                                            else State1 = 0;
                                            if (cMain.Objects[i].Device[j].Join[k].CoeffMultiply) 
                                                State2 = 1;
                                            else State2 = 0;
                                            if (cMain.Objects[i].Device[j].Join[k].ConvertParam) 
                                                State3 = 1;
                                            else State3 = 0;
                                            if (cMain.Objects[i].Device[j].Join[k].InSubscriberGroup)
                                                State4 = 1;
                                            else State4 = 0;
                                            
                                            DbCommand.CommandText =
                                                "insert into JOINS(DCID,OBJID,DEVID,JOINID,DEVINC,JOININC,TITLE,METERNUMBER,ENABLED,RECALC,TRANS_VQE,KTT,KTN,PTT,PTN,JN,DPXX,DPKZ,SNOM,LOSS_IN_COUNTER,LOSS_IN_TT,LOSS_IN_TN,NPATS_TYPE,NPATS_ID,NPATS_ID_IMP,ADDRESS,PLANTPLACE,COMMENTS,SUBSCRIBER,TREATY,RECEIPTMETHOD,BALANCEATTRIB,DIRECTOR,POWERSPEC,PHONE,CHECKDATE,SUBABONENT,KPE,KPM,TARIFFVOLTAGE,VOLTAGE,LOSS_IN_TRANS,LOSS_IN_LINE,TT_TYPE,TT_CURRENT1,TT_CURRENT2,TN_TYPE,TN_VOLTAGE1,TN_VOLTAGE2) values(" +
                                                FixIdentifierName(cMain.Objects[i].DCID.ToString()) + "," +
                                                FixIdentifierName(cMain.Objects[i].ID.ToString()) + "," +
                                                FixIdentifierName(cMain.Objects[i].Device[j].Join[k].DeviceID.ToString()) + "," +
                                                FixIdentifierName(cMain.Objects[i].Device[j].Join[k].ID.ToString()) + "," +
                                                FixIdentifierName(cMain.Objects[i].Device[j].ID.ToString()) + "," +
                                                FixIdentifierName(cMain.Objects[i].Device[j].Join[k].Index.ToString()) + "," +
                                                "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].Caption) + "'" + "," +                     
                                                FixIdentifierName(cMain.Objects[i].Device[j].Join[k].MeterNumber.ToString()) + "," +
                                                FixIdentifierName(State1.ToString()) + "," +
                                                FixIdentifierName(State2.ToString()) + "," +
                                                FixIdentifierName(State3.ToString()) + "," +
                                                FixIdentifierName(cMain.Objects[i].Device[j].Join[k].KTT.ToString()) + "," +
                                                FixIdentifierName(cMain.Objects[i].Device[j].Join[k].KTN.ToString()) + "," +
                                                FixIdentifierName(cMain.Objects[i].Device[j].Join[k].KTTClass.ToString().Replace(",", ".")) + "," +
                                                FixIdentifierName(cMain.Objects[i].Device[j].Join[k].KTNClass.ToString().Replace(",", ".")) + "," +
                                                "0," +
                                                FixIdentifierName(cMain.Objects[i].Device[j].Join[k].IdlingLosts.ToString().Replace(",", ".")) + "," +
                                                FixIdentifierName(cMain.Objects[i].Device[j].Join[k].ShortCircuitLosts.ToString().Replace(",", ".")) + "," +
                                                FixIdentifierName(cMain.Objects[i].Device[j].Join[k].TransformatorPower.ToString().Replace(",", ".")) + "," +
                                                FixIdentifierName(cMain.Objects[i].Device[j].Join[k].MeterLostsValue.ToString().Replace(",", ".")) + "," +
                                                FixIdentifierName(cMain.Objects[i].Device[j].Join[k].TTLostsValue.ToString().Replace(",", ".")) + "," +
                                                FixIdentifierName(cMain.Objects[i].Device[j].Join[k].TNLostsValue.ToString().Replace(",", ".")) + "," +
                                                "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].MeterCodeHPATS) + "'" + "," +
                                                "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].ExportCodeHPATS) + "'" + "," +
                                                "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].ImportCodeHPATS) + "'" + "," +
                                                "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].CollectPointAddress) + "'" + "," +
                                                "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].MeterPlacement) + "'" + "," +
                                                "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].Comments) + "'" + "," +
                                                "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].AbonentNumber) + "'" + "," +
                                                "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].AgreementNumber) + "'" + "," +
                                                "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].EvidenceMetod) + "'" + "," +
                                                "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].BalanceBelonging) + "'" + "," +
                                                "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].Director) + "'" + "," +
                                                "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].GeneralPES) + "'" + "," +
                                                "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].PhoneNumber) + "'" + "," +
                                                "to_date('" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].DTLastInspection.ToString()) + "','dd.mm.yyyy hh24:mi:ss')," +                                                
                                                FixIdentifierName(State4.ToString()) + "," +
                                                FixIdentifierName(cMain.Objects[i].Device[j].Join[k].KPE.ToString().Replace(",", ".")) + "," +
                                                FixIdentifierName(cMain.Objects[i].Device[j].Join[k].KPM.ToString().Replace(",", ".")) + "," +
                                                FixIdentifierName(cMain.Objects[i].Device[j].Join[k].UTariffLevel.ToString().Replace(",", ".")) + "," +
                                                FixIdentifierName(cMain.Objects[i].Device[j].Join[k].UTransformator.ToString().Replace(",", ".")) + "," +
                                                FixIdentifierName(cMain.Objects[i].Device[j].Join[k].TransformatorLosts.ToString().Replace(",", ".")) + "," +
                                                FixIdentifierName(cMain.Objects[i].Device[j].Join[k].LineLosts.ToString().Replace(",", ".")) + "," +
                                                "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].ITransformatorType) + "'" + "," +
                                                FixIdentifierName(cMain.Objects[i].Device[j].Join[k].INominalFirstTT.ToString().Replace(",", ".")) + "," +
                                                FixIdentifierName(cMain.Objects[i].Device[j].Join[k].INominalSecondTT.ToString().Replace(",", ".")) + "," +
                                                "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].UTransformatorType) + "'" + "," +
                                                FixIdentifierName(cMain.Objects[i].Device[j].Join[k].UNominalFirstTT.ToString().Replace(",", ".")) + "," +
                                                FixIdentifierName(cMain.Objects[i].Device[j].Join[k].UNominalSecondTT.ToString().Replace(",", ".")) + ")";

                                            ds.WriteLine(DbCommand.CommandText);
                                            if (DbCommand.ExecuteNonQuery() > 0)
                                            {
                                                cMain.Objects[i].Device[j].Join[k].ItemAction.DBExist = true;
                                                cMain.Objects[i].Device[j].Join[k].ItemAction.Changed = false;
                                            }
                                            AddToProgress(1);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Result = false;
                    new fExceptionMessageBox().Show(m_parent, cConst.ERROR_CAPTION, cConst.ERR_DB_EXCEPTION, DbCommand.CommandText + e.Message);
                   // MessageBox.Show(DbCommand.CommandText + e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return Result;
        }
        //Добавление в БД новых каналов учета для присоединений
        public static Boolean InsertNewChannels()
        {
            OleDbCommand DbCommand = null;
            Boolean Result = true;
            Byte State1;
            Int32 i, j, k, l;
            Int16 AR, Direction;

            if (DbConnect != null)
            {
                try
                {
                    DbCommand = DbConnect.CreateCommand();
                    //Добавление каналов учета для присоединений
                    for (i = 0; i < cMain.Objects.Length; i++)
                    {
                        if ((cMain.Objects[i].ItemAction.DBExist) &&
                            (!cMain.Objects[i].ItemAction.Deleted))
                        {
                            for (j = 0; j < cMain.Objects[i].Device.Length; j++)
                            {
                                if ((cMain.Objects[i].Device[j].ItemAction.DBExist) &&
                                    (!cMain.Objects[i].Device[j].ItemAction.Deleted))
                                {
                                    for (k = 0; k < cMain.Objects[i].Device[j].Join.Length; k++)
                                    {
                                        if ((cMain.Objects[i].Device[j].Join[k].ItemAction.DBExist) &&
                                            (!cMain.Objects[i].Device[j].Join[k].ItemAction.Deleted))
                                        {
                                            for (l = 0; l < cMain.Objects[i].Device[j].Join[k].Channel.Length; l++)
                                            {
                                                if ((!cMain.Objects[i].Device[j].Join[k].Channel[l].ItemAction.DBExist) &&
                                                    (!cMain.Objects[i].Device[j].Join[k].Channel[l].ItemAction.Deleted))
                                                {
                                                    if (cMain.Objects[i].Device[j].Join[k].Channel[l].CollectEnable)
                                                        State1 = 1;
                                                    else State1 = 0;
                                                    switch (cMain.Objects[i].Device[j].Join[k].Channel[l].EnergyType)
                                                    {
                                                        case 0:
                                                            AR = 0;
                                                            Direction = 1;
                                                            break;
                                                        case 1:
                                                            AR = 0;
                                                            Direction = -1;
                                                            break;
                                                        case 2:
                                                            AR = 1;
                                                            Direction = 1;
                                                            break;
                                                        case 3:
                                                            AR = 1;
                                                            Direction = -1;
                                                            break;
                                                        case 4:
                                                            AR = 2;
                                                            Direction = 1;
                                                            break;
                                                        case 5:
                                                            AR = 3;
                                                            Direction = 1;
                                                            break;
                                                        case 6:
                                                            AR = 3;
                                                            Direction = -1;
                                                            break;
                                                        case 7:
                                                            AR = 2;
                                                            Direction = -1;
                                                            break;
                                                        default:
                                                            AR = 0;
                                                            Direction = 1;
                                                            break;
                                                    }
                                                    DbCommand.CommandText =
                                                        "insert into CHANNELS(DCID,OBJID,DEVID,JOINID,CHANID,ENABLED,DIRECTION,AR,SERNUM,METER,NPATS_ID,NPATS_ID_IMP,TYPE63002,ASKP_ID) values(" +
                                                        FixIdentifierName(cMain.Objects[i].DCID.ToString()) + "," +
                                                        FixIdentifierName(cMain.Objects[i].ID.ToString()) + "," +
                                                        FixIdentifierName(cMain.Objects[i].Device[j].Join[k].DeviceID.ToString()) + "," +
                                                        FixIdentifierName(cMain.Objects[i].Device[j].Join[k].ID.ToString()) + "," +
                                                        FixIdentifierName(cMain.Objects[i].Device[j].Join[k].Channel[l].ID.ToString()) + "," +
                                                        FixIdentifierName(State1.ToString()) + "," +
                                                        FixIdentifierName(Direction.ToString()) + "," +
                                                        FixIdentifierName(AR.ToString()) + "," +
                                                        "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].Channel[l].MeterSerial) + "'" + "," +
                                                        FixIdentifierName(cMain.Objects[i].Device[j].Join[k].Channel[l].MeterID.ToString()) + "," +
                                                        "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].Channel[l].ExportNPATSCode) + "'" + "," +
                                                        "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].Channel[l].ImportNPATSCode) + "'" + "," +
                                                        "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].Channel[l].Value63002Code) + "'" + "," +
                                                        "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].Channel[l].ASKPIdentifier) + "'" + ")";//

                                                    if (DbCommand.ExecuteNonQuery() > 0)
                                                    {
                                                        cMain.Objects[i].Device[j].Join[k].Channel[l].ItemAction.DBExist = true;
                                                        cMain.Objects[i].Device[j].Join[k].Channel[l].ItemAction.Changed = false;
                                                    }
                                                    AddToProgress(1);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Result = false;
                    MessageBox.Show(DbCommand.CommandText + e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return Result;
        }
        //Добавление в БД новых линий электропередач для присоединений (Присутствует лажа с первичным ключем)
        public static Boolean InsertNewConnectionLines()
        {
            OleDbCommand DbCommand = null;
            Boolean Result = true;
            Int32 i, j, k, l;

            if (DbConnect != null)
            {
                try
                {
                    DbCommand = DbConnect.CreateCommand();
                    //Добавление линий электропередач для присоединений
                    for (i = 0; i < cMain.Objects.Length; i++)
                    {
                        if ((cMain.Objects[i].ItemAction.DBExist) &&
                            (!cMain.Objects[i].ItemAction.Deleted))
                        {
                            for (j = 0; j < cMain.Objects[i].Device.Length; j++)
                            {
                                if ((cMain.Objects[i].Device[j].ItemAction.DBExist) &&
                                    (!cMain.Objects[i].Device[j].ItemAction.Deleted))
                                {
                                    for (k = 0; k < cMain.Objects[i].Device[j].Join.Length; k++)
                                    {
                                        if ((cMain.Objects[i].Device[j].Join[k].ItemAction.DBExist) &&
                                            (!cMain.Objects[i].Device[j].Join[k].ItemAction.Deleted))
                                        {
                                            for (l = 0; l < cMain.Objects[i].Device[j].Join[k].ConnLineLosts.Length; l++)
                                            {
                                                if ((!cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ItemAction.DBExist) &&
                                                    (!cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ItemAction.Deleted))
                                                {
                                                    DbCommand.CommandText =
                                                        "insert into LINES(JOININC,LINEID,LENGTH,RESISTIVITY,VOLTAGE,LOSS_UD_INSN,LOSS_UD_INSR,CIRCUITS_AMOUNT) values(" +
                                                        FixIdentifierName(cMain.Objects[i].Device[j].Join[k].Index.ToString()) + "," +
                                                        "NULL," +//cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ID.ToString() + "," +
                                                        FixIdentifierName(cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].LineLength.ToString().Replace(",", ".")) + "," +
                                                        FixIdentifierName(cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].Resistance.ToString().Replace(",", ".")) + "," +
                                                        FixIdentifierName(cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].UNominal.ToString().Replace(",", ".")) + "," +
                                                        FixIdentifierName(cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].CableLost.ToString().Replace(",", ".")) + "," +
                                                        FixIdentifierName(cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].AirLost.ToString().Replace(",", ".")) + "," +
                                                        FixIdentifierName(cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].CircuitsAmount.ToString()) + ")";
                                                    if (DbCommand.ExecuteNonQuery() > 0)
                                                    {
                                                        cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ItemAction.DBExist = true;
                                                        cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ItemAction.Changed = false;
                                                    }
                                                    AddToProgress(1);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Result = false;
                    MessageBox.Show(DbCommand.CommandText + e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return Result;
        }
        //Добавление в БД новых групп отчетов для присоединений
        public static Boolean InsertNewReportGroups()
        {
            OleDbCommand DbCommand = null;
            Boolean Result = true;
            Int32 i, j, k, l;

            if (DbConnect != null)
            {
                try
                {
                    DbCommand = DbConnect.CreateCommand();
                    //Добавление групп отчетов для присоединений
                    for (i = 0; i < cMain.Objects.Length; i++)
                    {
                        if ((cMain.Objects[i].ItemAction.DBExist) &&
                            (!cMain.Objects[i].ItemAction.Deleted))
                        {
                            for (j = 0; j < cMain.Objects[i].Device.Length; j++)
                            {
                                if ((cMain.Objects[i].Device[j].ItemAction.DBExist) &&
                                    (!cMain.Objects[i].Device[j].ItemAction.Deleted))
                                {
                                    for (k = 0; k < cMain.Objects[i].Device[j].Join.Length; k++)
                                    {
                                        if ((cMain.Objects[i].Device[j].Join[k].ItemAction.DBExist) &&
                                            (!cMain.Objects[i].Device[j].Join[k].ItemAction.Deleted))
                                        {
                                            for (l = 0; l < cMain.Objects[i].Device[j].Join[k].ReportGroup.Length; l++)
                                            {
                                                if ((!cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ItemAction.DBExist) &&
                                                    (!cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ItemAction.Deleted))
                                                {
                                                    DbCommand.CommandText =
                                                        "insert into JOIN_GROUP(DCID,OBJID,DEVID,JOINID,REPGROUPID,REPGROUP_REF) values(" +
                                                        FixIdentifierName(cMain.Objects[i].DCID.ToString()) + "," +
                                                        FixIdentifierName(cMain.Objects[i].ID.ToString()) + "," +
                                                        FixIdentifierName(cMain.Objects[i].Device[j].Join[k].DeviceID.ToString()) + "," +
                                                        FixIdentifierName(cMain.Objects[i].Device[j].Join[k].ID.ToString()) + "," +
                                                        FixIdentifierName(cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ID.ToString()) + "," +
                                                        FixIdentifierName(cMain.Objects[i].Device[j].Join[k].ReportGroup[l].RGType.ToString()) + ")";

                                                    if (DbCommand.ExecuteNonQuery() > 0)
                                                    {
                                                        cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ItemAction.DBExist = true;
                                                        cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ItemAction.Changed = false;
                                                    }
                                                    AddToProgress(1);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Result = false;
                    MessageBox.Show(DbCommand.CommandText + e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return Result;
        }

        //Обновление в БД справочника типов устройств
        public static Boolean UpdateDeviceTypeList()
        {
            OleDbCommand DbCommand = null;
            Boolean Result = true;
            Int32 i;

            if (DbConnect != null)
            {
                try
                {
                    DbCommand = DbConnect.CreateCommand();
                    //Обновление типов устройств в справочнике
                    for (i = 0; i < cMain.DevTypeList.Length; i++)
                    {
                        if ((cMain.DevTypeList[i].ItemAction.DBExist) &&
                            (cMain.DevTypeList[i].ItemAction.Changed) &&
                            (!cMain.DevTypeList[i].ItemAction.Deleted))
                        {
                            DbCommand.CommandText =
                                "update DEVREF set" +                        
                                " TITLE=" + "'" + FixIdentifierName(cMain.DevTypeList[i].Caption) + "'" + "," +
                                " DEVTYPE=" + FixIdentifierName(cMain.DevTypeList[i].DeviceKind.ToString()) + "," +
                                " DRIVER=" + "''" + "," +
                                " CHANNELS=" + FixIdentifierName(cMain.DevTypeList[i].ChannelCount.ToString()) + "," +
                                " DEVICENAME=" + "'" + FixIdentifierName(cMain.DevTypeList[i].DeviceDllName) + "'" + "," +
                                " PROTOCOLNAME=" + "'" + FixIdentifierName(cMain.DevTypeList[i].ProtocolDLLName) + "'" + "," +
                                " FILECODESNPATS=" + "'" + FixIdentifierName(cMain.DevTypeList[i].FileCodeNPATS) + "'" + "," +
                                " SETTINGS=" + "?" +
                                " where DEVID=" + FixIdentifierName(cMain.DevTypeList[i].ID.ToString()); 
                            DbCommand.Parameters.Clear();
                            DbCommand.Parameters.Add("@SETTINGS", OleDbType.LongVarBinary, cMain.DevTypeList[i].ProtocolSetting.Length, "SETTINGS").Value = cMain.DevTypeList[i].ProtocolSetting;
                            if (DbCommand.ExecuteNonQuery() > 0) 
                                cMain.DevTypeList[i].ItemAction.Changed = false;
                            AddToProgress(1);
                        }
                    }
                }
                catch (Exception e)
                {
                    Result = false;
                    MessageBox.Show(DbCommand.CommandText + e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return Result;
        }
        //Обновление в БД справо" NPATS_IDчника счетчиков
        public static Boolean UpdateMeterList()
        {
            OleDbCommand DbCommand = null;
            Boolean Result = true;
            Int32 i;

            if (DbConnect != null)
            {
                try
                {
                    DbCommand = DbConnect.CreateCommand();
                    //Обновление типов счетчиков в справочнике
                    for (i = 0; i < cMain.MeterList.Length; i++)
                    {
                        if ((cMain.MeterList[i].ItemAction.DBExist) &&
                            (cMain.MeterList[i].ItemAction.Changed) &&
                            (!cMain.MeterList[i].ItemAction.Deleted))
                        {
                            DbCommand.CommandText =
                                "update METERS set" +                                
                                " TITLE=" + "'" + FixIdentifierName(cMain.MeterList[i].Caption) + "'" + "," +
                                " PREC=" + FixIdentifierName(cMain.MeterList[i].Precision.ToString().Replace(",", ".")) + "," +
                                " INTDIGITS=" + FixIdentifierName(cMain.MeterList[i].BeforeComma.ToString()) + "," +
                                " DECIMALDIGITS=" + FixIdentifierName(cMain.MeterList[i].AfterComma.ToString()) + "," +
                                " KOEFF=" + FixIdentifierName(cMain.MeterList[i].MeterConst.ToString()) + "," +
                                " PHASETYPE=" + FixIdentifierName(cMain.MeterList[i].Phase.ToString()) + "," +
                                " SELFUSE=" + FixIdentifierName(cMain.MeterList[i].SelfDemand.ToString().Replace(",", ".")) +
                                " where METER=" + FixIdentifierName(cMain.MeterList[i].ID.ToString());
                            if (DbCommand.ExecuteNonQuery() > 0)                             
                                cMain.MeterList[i].ItemAction.Changed = false;
                            AddToProgress(1);
                        }
                    }
                }
                catch (Exception e)
                {
                    Result = false;
                    MessageBox.Show(DbCommand.CommandText + e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return Result;
        }
        //Обновление в БД справочника каналов связи
        public static Boolean UpdateCommChanList()
        {
            OleDbCommand DbCommand = null;
            Boolean Result = true;
            Int32 i;

            if (DbConnect != null)
            {
                try
                {
                    DbCommand = DbConnect.CreateCommand();
                    //Обновление каналов связи в справочнике
                    for (i = 0; i < cMain.CommChanList.Length; i++)
                    {
                        if ((cMain.CommChanList[i].ItemAction.DBExist) &&
                            (cMain.CommChanList[i].ItemAction.Changed) &&
                            (!cMain.CommChanList[i].ItemAction.Deleted))
                        {
                            DbCommand.CommandText =
                                "update COMCHAN set" +                                
                                " COMNAME=" + "'" + FixIdentifierName(cMain.CommChanList[i].DllName) + "'" + "," +
                                " NAME=" + "'" + FixIdentifierName(cMain.CommChanList[i].Caption) + "'" + "," +
                                " PORT=" + FixIdentifierName(cMain.CommChanList[i].GroupID.ToString()) + "," +
                                " SETTING=" + "?" +
                                " where CHANID=" + FixIdentifierName(cMain.CommChanList[i].ID.ToString());
                            DbCommand.Parameters.Clear();
                            DbCommand.Parameters.Add("@SETTING", OleDbType.LongVarBinary, cMain.CommChanList[i].Setting.Length, "SETTING").Value = cMain.CommChanList[i].Setting;
                            if (DbCommand.ExecuteNonQuery() > 0)
                                cMain.CommChanList[i].ItemAction.Changed = false;
                            AddToProgress(1);
                        }
                    }
                }
                catch (Exception e)
                {
                    Result = false;
                    MessageBox.Show(DbCommand.CommandText + e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return Result;
        }
        //Обновление в БД справочника тарифов
        public static Boolean UpdateTariffList()
        {
            OleDbCommand DbCommand = null;
            Boolean Result = true;
            Int32 i;

            if (DbConnect != null)
            {
                try
                {
                    DbCommand = DbConnect.CreateCommand();
                    //Обновление тарифов в справочнике
                    for (i = 0; i < cMain.TariffList.Length; i++)
                    {
                        if ((cMain.TariffList[i].ItemAction.DBExist) &&
                            (cMain.TariffList[i].ItemAction.Changed) &&
                            (!cMain.TariffList[i].ItemAction.Deleted))
                        {
                            DbCommand.CommandText =
                                "update TARIFF set" +                                
                                " NM=" + "'" + FixIdentifierName(cMain.TariffList[i].Caption) + "'" + "," +
                                " COLOR=" + FixIdentifierName(cMain.TariffList[i].FillColor.ToString()) +
                                " where IDTF=" + FixIdentifierName(cMain.TariffList[i].ID.ToString());
                            if (DbCommand.ExecuteNonQuery() > 0)                            
                                cMain.TariffList[i].ItemAction.Changed = false;
                            AddToProgress(1);
                        }
                    }
                }
                catch (Exception e)
                {
                    Result = false;
                    MessageBox.Show(DbCommand.CommandText + e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return Result;
        }
        //Обновление в БД справочника пользователей
        public static Boolean UpdateUserList()
        {
            OleDbCommand DbCommand = null;
            Boolean Result = true;
            Int32 i;

            if (DbConnect != null)
            {
                try
                {
                    DbCommand = DbConnect.CreateCommand();
                    //Обновление пользователей в справочнике
                    for (i = 0; i < cMain.UserList.Length; i++)
                    {
                        if ((cMain.UserList[i].ItemAction.DBExist) &&
                            (cMain.UserList[i].ItemAction.Changed) &&
                            (!cMain.UserList[i].ItemAction.Deleted))
                        {
                            DbCommand.CommandText =
                                "update TELECONTROL_USERS set" +
                                " TCUSER=" + "'" + FixIdentifierName(cMain.UserList[i].Caption) + "'" + "," +
                                " TCPASSWORD=" + "'" + FixIdentifierName(cMain.UserList[i].Password) + "'" + "," +
                                " TCURID=" + FixIdentifierName(cMain.UserList[i].AccessID.ToString()) +
                                " where TCUSERID=" + FixIdentifierName(cMain.UserList[i].ID.ToString());
                            if (DbCommand.ExecuteNonQuery() > 0)
                                cMain.UserList[i].ItemAction.Changed = false;
                            AddToProgress(1);
                        }
                    }
                }
                catch (Exception e)
                {
                    Result = false;
                    MessageBox.Show(DbCommand.CommandText + e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return Result;
        }
        //Обновление в БД территориальных объединений
        public static Boolean UpdateDC()
        {
            OleDbCommand DbCommand = null;
            Boolean Result = true;
            Int32 i;

            if (DbConnect != null)
            {
                try
                {
                    DbCommand = DbConnect.CreateCommand();
                    //Обновление территориальных объединений
                    for (i = 0; i < cMain.DC.Length; i++)
                    {
                        if ((cMain.DC[i].ItemAction.DBExist) &&
                            (cMain.DC[i].ItemAction.Changed) &&
                            (!cMain.DC[i].ItemAction.Deleted))
                        {
                            DbCommand.CommandText =
                                "update DC set" +                        
                                " NAME=" + "'" + FixIdentifierName(cMain.DC[i].Caption) + "'" +
                                " where PARENT=" + FixIdentifierName(cMain.DC[i].ParentID.ToString()) + 
                                " and ID=" + FixIdentifierName(cMain.DC[i].ID.ToString());
                            if (DbCommand.ExecuteNonQuery() > 0)
                                cMain.DC[i].ItemAction.Changed = false;
                            AddToProgress(1);
                        }
                    }
                }
                catch (Exception e)
                {
                    Result = false;
                    MessageBox.Show(DbCommand.CommandText + e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return Result;
        }
        //Обновление в БД объектов учета
        public static Boolean UpdateObjects()
        {
            OleDbCommand DbCommand = null;
            Boolean Result = true;
            Int32 i, j, Count;
            Byte State1, State2;
            String ObjCommChan, ObjAddCommChan, ExportDCID, ExportObjID;
            Boolean[] ItemChange;
            Boolean NextTime;

            if (DbConnect != null)
            {
                try
                {
                    DbCommand = DbConnect.CreateCommand();
                    //Обновление объектов учета
                    for (i = 0; i < cMain.Objects.Length; i++)
                    {
                        if ((cMain.Objects[i].ItemAction.DBExist) &&
                            (cMain.Objects[i].ItemAction.Changed) &&
                            (!cMain.Objects[i].ItemAction.Deleted))
                        {
                            if (cMain.Objects[i].CollectionState) State1 = 1;
                            else State1 = 0;
                            
                            ExportDCID = "NULL";
                            ExportObjID = "NULL";
                            if (cMain.Objects[i].IsExported)
                            {
                                State2 = 1;
                                if ((cMain.Objects[i].ExportDCID >= 0) && (cMain.Objects[i].ExportObjID >= 0))
                                {
                                    ExportDCID = cMain.Objects[i].ExportDCID.ToString();
                                    ExportObjID = cMain.Objects[i].ExportObjID.ToString();
                                }
                            }
                            else State2 = 0;  

                            if (cMain.Objects[i].CommChan >= 0) ObjCommChan = cMain.Objects[i].CommChan.ToString();
                            else ObjCommChan = "NULL";
                            if (cMain.Objects[i].AddCommChan >= 0) ObjAddCommChan = cMain.Objects[i].AddCommChan.ToString();
                            else ObjAddCommChan = "NULL";
                            DbCommand.CommandText =
                                "update DSROBJ set" +                                
                                " NAME=" + "'" + FixIdentifierName(cMain.Objects[i].Caption) + "'" + "," +
                                " GATE=" + FixIdentifierName(cMain.Objects[i].ComputerAddress.ToString()) + "," +
                                " FCHAN=" + FixIdentifierName(ObjCommChan) + "," + 
                                " RCHAN=" + FixIdentifierName(ObjAddCommChan) + "," + 
                                " PRIORITY=1" + "," +
                                " ISACTIVE=" + FixIdentifierName(State1.ToString()) + "," +
                                " DATESTART=" + "to_date('" + FixIdentifierName(cMain.Objects[i].CollectionStartDT.ToString()) + "','dd.mm.yyyy hh24:mi:ss'), " +
                                " NPATS_ID=" + "'" + FixIdentifierName(cMain.Objects[i].CodeNPATS) + "'" + "," +
                                " KOD63002=" + "'" + FixIdentifierName(cMain.Objects[i].Code63002) + "'" + "," +
                                " EXPORTACTIVE=" + FixIdentifierName(State2.ToString()) + "," +
                                " DCIDEXP=" + FixIdentifierName(ExportDCID) + "," +
                                " OBJIDEXP=" + FixIdentifierName(ExportObjID) + "," +
                                " TCPERIODTYPE=" + FixIdentifierName(cMain.Objects[i].tcPeriodType.ToString()) + "," +
                                " TCPERIODCOUNT=" + FixIdentifierName(cMain.Objects[i].tcPeriodCount.ToString()) +
                                " where DCID=" + FixIdentifierName(cMain.Objects[i].DCID.ToString()) +
                                " and OBJID=" + FixIdentifierName(cMain.Objects[i].ID.ToString());
                            if (DbCommand.ExecuteNonQuery() > 0)
                            {
                                //Обновление тарифного расписания
                                Count = 0;
                                NextTime = true;
                                ItemChange = new Boolean[cMain.Objects[i].Schedule.Length];
                                for (j = 0; j < ItemChange.Length; j++) ItemChange[j] = false;
                                
                                while ((NextTime) && (Count < ItemChange.Length))
                                {
                                    NextTime = false;
                                    for (j = 0; j < cMain.Objects[i].Schedule.Length; j++)
                                    {
                                        if (!ItemChange[j])
                                        {
                                            if (cMain.Objects[i].Schedule[j].CollectOn) State1 = 1;
                                            else 
                                                State1 = 0;

                                                DbCommand.CommandText =
                                                    "update SCHEDULE set" +
                                                    " SACTIVE=" + State1.ToString() + "," +
                                                    " PERTYPECOLL=" +
                                                    cMain.Objects[i].Schedule[j].CPeriodType.ToString() + "," +
                                                    " PERIODCOLL=" +
                                                    cMain.Objects[i].Schedule[j].CPeriodCount.ToString() + "," +
                                                    " PERTYPEDATA=" +
                                                    cMain.Objects[i].Schedule[j].DPeriodType.ToString() + "," +
                                                    " PERIODDATA=" +
                                                    cMain.Objects[i].Schedule[j].DPeriodCount.ToString() + "," +
                                                    " DEPTHTYPECOLLHOLES=" +
                                                    cMain.Objects[i].Schedule[j].HPeriodType.ToString() + "," +
                                                    " DEPTHCOLLHOLES=" +
                                                    cMain.Objects[i].Schedule[j].HPeriodCount.ToString() +
                                                    " where DCID=" + cMain.Objects[i].DCID.ToString() +
                                                    " and OBJID=" + cMain.Objects[i].ID.ToString() +
                                                    " and SHEDID=" + cMain.Objects[i].Schedule[j].ID.ToString() +
                                                    " and PERTYPEDATA=" +
                                                    cMain.Objects[i].Schedule[j].PeriodTypeID.ToString() +
                                                    " and PERIODDATA=" +
                                                    cMain.Objects[i].Schedule[j].PeriodCountID.ToString();

                                            try
                                            {
                                                if (DbCommand.ExecuteNonQuery() > 0)
                                                {
                                                    ItemChange[j] = true;
                                                    cMain.Objects[i].Schedule[j].PeriodTypeID = cMain.Objects[i].Schedule[j].DPeriodType;
                                                    cMain.Objects[i].Schedule[j].PeriodCountID = cMain.Objects[i].Schedule[j].DPeriodCount;
                                                }
                                            }
                                            catch
                                            {
                                                NextTime = true;
                                            }
                                        }
                                    }
                                    Count++;
                                }
                                cMain.Objects[i].ItemAction.Changed = false;
                            }
                            AddToProgress(1);
                        }
                    }
                }
                catch (Exception e)
                {
                    Result = false;
                    MessageBox.Show(DbCommand.CommandText + e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return Result;
        }
        //Обновление в БД устройств для объектов учета
        public static Boolean UpdateObjectDevices()
        {
            OleDbCommand DbCommand = null;
            Boolean Result = true;
            Int32 i, j;
            Byte State1;

            if (DbConnect != null)
            {
                try
                {
                    DbCommand = DbConnect.CreateCommand();
                    //Обновление устройств для объектов учета
                    for (i = 0; i < cMain.Objects.Length; i++)
                    {
                        if ((cMain.Objects[i].ItemAction.DBExist) &&
                            (!cMain.Objects[i].ItemAction.Deleted))
                        {
                            for (j = 0; j < cMain.Objects[i].Device.Length; j++)
                            {
                                if ((cMain.Objects[i].Device[j].ItemAction.DBExist) &&
                                    (cMain.Objects[i].Device[j].ItemAction.Changed) &&
                                    (!cMain.Objects[i].Device[j].ItemAction.Deleted))
                                {
                                    if (cMain.Objects[i].Device[j].IsExported)
                                        State1 = 1;
                                    else State1 = 0;
                                    DbCommand.CommandText =
                                        "update DEVICES set" +                                        
                                        " DEVICE=" + FixIdentifierName(cMain.Objects[i].Device[j].DeviceID.ToString()) + "," +
                                        " NET=" + FixIdentifierName(cMain.Objects[i].Device[j].NetAddress.ToString()) + "," +
                                        " DEVID=" + FixIdentifierName(cMain.Objects[i].Device[j].Address.ToString()) + "," +
                                        " IDENTIFIER=" + "'" + FixIdentifierName(cMain.Objects[i].Device[j].Identifier) + "'" + "," +
                                        " SERNUM=" + "'" + FixIdentifierName(cMain.Objects[i].Device[j].SerialNumber) + "'" + "," +
                                        " LOGDATEEND=" + "to_date('" + FixIdentifierName(cMain.Objects[i].Device[j].JournalLastDT.ToString()) + "','dd.mm.yyyy hh24:mi:ss')," +
                                        " LASTEVENTNUMBER=" + FixIdentifierName(cMain.Objects[i].Device[j].LastEventIdx.ToString()) + "," +
                                        " EXPORTACTIVE=" + FixIdentifierName(State1.ToString()) + "," +
                                        " LOGIN=" + "'" + FixIdentifierName(cMain.Objects[i].Device[j].UserName) + "'" + "," +
                                        " PASS=" + "'" + FixIdentifierName(cMain.Objects[i].Device[j].UserPassword) + "'" + "," +
                                        " SETTINGS=" + "?" +
                                        " where DCID=" + FixIdentifierName(cMain.Objects[i].DCID.ToString()) + 
                                        " and OBJID=" + FixIdentifierName(cMain.Objects[i].ID.ToString()) + 
                                        " and DEVINC=" + FixIdentifierName(cMain.Objects[i].Device[j].ID.ToString());
                                    DbCommand.Parameters.Clear();
                                    if (cMain.Objects[i].Device[j].ProtocolSetting.Length > 0)
                                        DbCommand.Parameters.Add("@SETTINGS", OleDbType.LongVarBinary, cMain.Objects[i].Device[j].ProtocolSetting.Length, "SETTINGS").Value = cMain.Objects[i].Device[j].ProtocolSetting;
                                    else DbCommand.Parameters.Add("@SETTINGS", OleDbType.LongVarBinary, cMain.Objects[i].Device[j].ProtocolSetting.Length, "SETTINGS").Value = null;
                                    if (DbCommand.ExecuteNonQuery() > 0)                                    
                                        cMain.Objects[i].Device[j].ItemAction.Changed = false;
                                    AddToProgress(1);
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Result = false;
                    MessageBox.Show(DbCommand.CommandText + e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return Result;
        }
        //Обновление в БД коммутационного оборудования для устройств
        public static Boolean UpdateDeviceСommEqupment()
        {
            OleDbCommand DbCommand = null;
            Boolean Result = true;
            Int32 i, j, k, Count, PCount;
            Boolean NextTime;

            if (DbConnect != null)
            {
                try
                {
                    DbCommand = DbConnect.CreateCommand();
                    //Обновление коммутационного оборудования для устройств
                    for (i = 0; i < cMain.Objects.Length; i++)
                    {
                        if ((cMain.Objects[i].ItemAction.DBExist) &&
                            (!cMain.Objects[i].ItemAction.Deleted))
                        {
                            for (j = 0; j < cMain.Objects[i].Device.Length; j++)
                            {
                                if ((cMain.Objects[i].Device[j].ItemAction.DBExist) &&
                                    (!cMain.Objects[i].Device[j].ItemAction.Deleted))
                                {
                                    PCount = 0;
                                    for (k = 0; k < cMain.Objects[i].Device[j].CommEquipment.Length; k++)
                                    {
                                        if ((cMain.Objects[i].Device[j].CommEquipment[k].ItemAction.DBExist) &&
                                            (cMain.Objects[i].Device[j].CommEquipment[k].ItemAction.Changed) &&
                                            (!cMain.Objects[i].Device[j].CommEquipment[k].ItemAction.Deleted)) PCount++;
                                    }                          
                                    Count = 0;
                                    NextTime = true;
                                    while ((NextTime) && (Count < cMain.Objects[i].Device[j].CommEquipment.Length * 3))
                                    {
                                        NextTime = false;
                                        for (k = 0; k < cMain.Objects[i].Device[j].CommEquipment.Length; k++)
                                        {
                                            if ((cMain.Objects[i].Device[j].CommEquipment[k].ItemAction.DBExist) &&
                                                (cMain.Objects[i].Device[j].CommEquipment[k].ItemAction.Changed) &&
                                                (!cMain.Objects[i].Device[j].CommEquipment[k].ItemAction.Deleted))
                                            {
                                                DbCommand.CommandText =
                                                    "update IDC_STATE set" +
                                                    " IDSTATE=" + FixIdentifierName(cMain.Objects[i].Device[j].CommEquipment[k].ChannelNumber.ToString()) + "," +
                                                    " NAME=" + "'" + FixIdentifierName(cMain.Objects[i].Device[j].CommEquipment[k].Caption) + "'" +
                                                    " where DCID=" + FixIdentifierName(cMain.Objects[i].DCID.ToString()) +
                                                    " and OBJID=" + FixIdentifierName(cMain.Objects[i].ID.ToString()) +
                                                    " and DEVINC=" + FixIdentifierName(cMain.Objects[i].Device[j].ID.ToString()) +
                                                    " and IDINC=" + FixIdentifierName(cMain.Objects[i].Device[j].CommEquipment[k].ID.ToString());
                                                try
                                                {
                                                    if (DbCommand.ExecuteNonQuery() > 0)
                                                        cMain.Objects[i].Device[j].CommEquipment[k].ItemAction.Changed = false;
                                                }
                                                catch { NextTime = true; }
                                            }
                                        }
                                        Count++;
                                    }
                                    AddToProgress(PCount);
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Result = false;
                    MessageBox.Show(DbCommand.CommandText + e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return Result;
        }
        //Обновление в БД присоединений для устройств
        public static Boolean UpdateDeviceJoin()
        {
            OleDbCommand DbCommand = null;
            Boolean Result = true;
            Byte State1, State2, State3, State4;
            Int32 i, j, k;

            if (DbConnect != null)
            {
                try
                {
                    DbCommand = DbConnect.CreateCommand();
                    //Обновление присоединений для устройств
                    for (i = 0; i < cMain.Objects.Length; i++)
                    {
                        if ((cMain.Objects[i].ItemAction.DBExist) &&
                            (!cMain.Objects[i].ItemAction.Deleted))
                        {
                            for (j = 0; j < cMain.Objects[i].Device.Length; j++)
                            {
                                if ((cMain.Objects[i].Device[j].ItemAction.DBExist) &&
                                    (!cMain.Objects[i].Device[j].ItemAction.Deleted))
                                {
                                    for (k = 0; k < cMain.Objects[i].Device[j].Join.Length; k++)
                                    {
                                        if ((cMain.Objects[i].Device[j].Join[k].ItemAction.DBExist) &&
                                            (cMain.Objects[i].Device[j].Join[k].ItemAction.Changed) &&
                                            (!cMain.Objects[i].Device[j].Join[k].ItemAction.Deleted))
                                        {
                                            if (cMain.Objects[i].Device[j].Join[k].CollectEnable)
                                                State1 = 1;
                                            else State1 = 0;
                                            if (cMain.Objects[i].Device[j].Join[k].CoeffMultiply)
                                                State2 = 1;
                                            else State2 = 0;
                                            if (cMain.Objects[i].Device[j].Join[k].ConvertParam)
                                                State3 = 1;
                                            else State3 = 0;
                                            if (cMain.Objects[i].Device[j].Join[k].InSubscriberGroup)
                                                State4 = 1;
                                            else State4 = 0;
                                            DbCommand.CommandText =
                                                "update JOINS set" +
                                                " DEVINC=" + FixIdentifierName(cMain.Objects[i].Device[j].ID.ToString()) + "," +
                                                " JOININC=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].Index.ToString()) + "," +
                                                " TITLE=" + "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].Caption) + "'" + "," +
                                                " METERNUMBER=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].MeterNumber.ToString()) + "," +
                                                " ENABLED=" + FixIdentifierName(State1.ToString()) + "," +
                                                " RECALC=" + FixIdentifierName(State2.ToString()) + "," +
                                                " TRANS_VQE=" + FixIdentifierName(State3.ToString()) + "," +
                                                " KTT=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].KTT.ToString()) + "," +
                                                " KTN=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].KTN.ToString()) + "," +
                                                " PTT=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].KTTClass.ToString().Replace(",", ".")) + "," +
                                                " PTN=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].KTNClass.ToString().Replace(",", ".")) + "," +
                                                " JN=0," +
                                                " DPXX=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].IdlingLosts.ToString().Replace(",", ".")) + "," +
                                                " DPKZ=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].ShortCircuitLosts.ToString().Replace(",", ".")) + "," +
                                                " SNOM=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].TransformatorPower.ToString().Replace(",", ".")) + "," +
                                                " LOSS_IN_COUNTER=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].MeterLostsValue.ToString().Replace(",", ".")) + "," +
                                                " LOSS_IN_TT=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].TTLostsValue.ToString().Replace(",", ".")) + "," +
                                                " LOSS_IN_TN=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].TNLostsValue.ToString().Replace(",", ".")) + "," +
                                                " NPATS_TYPE=" + "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].MeterCodeHPATS) + "'" + "," +
                                                " NPATS_ID=" + "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].ExportCodeHPATS) + "'" + "," +
                                                " NPATS_ID_IMP=" + "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].ImportCodeHPATS) + "'" + "," +
                                                " ADDRESS=" + "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].CollectPointAddress) + "'" + "," +
                                                " PLANTPLACE=" + "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].MeterPlacement) + "'" + "," +
                                                " COMMENTS=" + "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].Comments) + "'" + "," +
                                                " SUBSCRIBER=" + "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].AbonentNumber) + "'" + "," +
                                                " TREATY=" + "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].AgreementNumber) + "'" + "," +
                                                " RECEIPTMETHOD=" + "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].EvidenceMetod) + "'" + "," +
                                                " BALANCEATTRIB=" + "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].BalanceBelonging) + "'" + "," +
                                                " DIRECTOR=" + "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].Director) + "'" + "," +
                                                " POWERSPEC=" + "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].GeneralPES) + "'" + "," +
                                                " PHONE=" + "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].PhoneNumber) + "'" + "," +
                                                " CHECKDATE=" + "to_date('" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].DTLastInspection.ToString()) + "','dd.mm.yyyy hh24:mi:ss')," +
                                                " SUBABONENT=" + FixIdentifierName(State4.ToString()) + "," +
                                                " KPE=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].KPE.ToString().Replace(",", ".")) + "," +
                                                " KPM=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].KPM.ToString().Replace(",", ".")) + "," +
                                                " TARIFFVOLTAGE=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].UTariffLevel.ToString().Replace(",", ".")) + "," +
                                                " VOLTAGE=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].UTransformator.ToString().Replace(",", ".")) + "," +
                                                " LOSS_IN_TRANS=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].TransformatorLosts.ToString().Replace(",", ".")) + "," +
                                                " LOSS_IN_LINE=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].LineLosts.ToString().Replace(",", ".")) + "," +
                                                " TT_TYPE=" + "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].ITransformatorType) + "'" + "," +
                                                " TT_CURRENT1=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].INominalFirstTT.ToString().Replace(",", ".")) + "," +
                                                " TT_CURRENT2=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].INominalSecondTT.ToString().Replace(",", ".")) + "," +
                                                " TN_TYPE=" + "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].UTransformatorType) + "'" + "," +
                                                " TN_VOLTAGE1=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].UNominalFirstTT.ToString().Replace(",", ".")) + "," +
                                                " TN_VOLTAGE2=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].UNominalSecondTT.ToString().Replace(",", ".")) + 
                                                " where DCID=" + FixIdentifierName(cMain.Objects[i].DCID.ToString()) +
                                                " and OBJID=" + FixIdentifierName(cMain.Objects[i].ID.ToString()) +
                                                " and DEVID=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].DeviceID.ToString()) +
                                                " and JOINID=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].ID.ToString());

                                            if (DbCommand.ExecuteNonQuery() > 0)
                                                cMain.Objects[i].Device[j].Join[k].ItemAction.Changed = false;
                                            AddToProgress(1);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Result = false;
                    MessageBox.Show(DbCommand.CommandText + e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return Result;
        }
        //Обновление в БД каналов учета для присоединений
        public static Boolean UpdateJoinChannels()
        {
            OleDbCommand DbCommand = null;
            Boolean Result = true;
            Byte State1;
            Int32 i, j, k, l;
            Int16 AR, Direction;

            if (DbConnect != null)
            {
                try
                {
                    DbCommand = DbConnect.CreateCommand();
                    //Обновление каналов учета для присоединений
                    for (i = 0; i < cMain.Objects.Length; i++)
                    {
                        if ((cMain.Objects[i].ItemAction.DBExist) &&
                            (!cMain.Objects[i].ItemAction.Deleted))
                        {
                            for (j = 0; j < cMain.Objects[i].Device.Length; j++)
                            {
                                if ((cMain.Objects[i].Device[j].ItemAction.DBExist) &&
                                    (!cMain.Objects[i].Device[j].ItemAction.Deleted))
                                {
                                    for (k = 0; k < cMain.Objects[i].Device[j].Join.Length; k++)
                                    {
                                        if ((cMain.Objects[i].Device[j].Join[k].ItemAction.DBExist) &&
                                            (!cMain.Objects[i].Device[j].Join[k].ItemAction.Deleted))
                                        {
                                            for (l = 0; l < cMain.Objects[i].Device[j].Join[k].Channel.Length; l++)
                                            {
                                                if ((cMain.Objects[i].Device[j].Join[k].Channel[l].ItemAction.DBExist) &&
                                                    (cMain.Objects[i].Device[j].Join[k].Channel[l].ItemAction.Changed) &&
                                                    (!cMain.Objects[i].Device[j].Join[k].Channel[l].ItemAction.Deleted))
                                                {
                                                    if (cMain.Objects[i].Device[j].Join[k].Channel[l].CollectEnable)
                                                        State1 = 1;
                                                    else State1 = 0;
                                                    switch (cMain.Objects[i].Device[j].Join[k].Channel[l].EnergyType)
                                                    {
                                                        case 0:
                                                            AR = 0;
                                                            Direction = 1;
                                                            break;
                                                        case 1:
                                                            AR = 0;
                                                            Direction = -1;
                                                            break;
                                                        case 2:
                                                            AR = 1;
                                                            Direction = 1;
                                                            break;
                                                        case 3:
                                                            AR = 1;
                                                            Direction = -1;
                                                            break;
                                                        case 4:
                                                            AR = 2;
                                                            Direction = 1;
                                                            break;
                                                        case 5:
                                                            AR = 3;
                                                            Direction = 1;
                                                            break;
                                                        case 6:
                                                            AR = 3;
                                                            Direction = -1;
                                                            break;
                                                        case 7:
                                                            AR = 2;
                                                            Direction = -1;
                                                            break;
                                                        default:
                                                            AR = 0;
                                                            Direction = 1;
                                                            break;
                                                    }
                                                    DbCommand.CommandText =
                                                        "update CHANNELS set" +                                                        
                                                        " ENABLED=" + FixIdentifierName(State1.ToString()) + "," +
                                                        " DIRECTION=" + FixIdentifierName(Direction.ToString()) + "," +
                                                        " AR=" + FixIdentifierName(AR.ToString()) + "," +
                                                        " SERNUM=" + "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].Channel[l].MeterSerial) + "'" + "," +
                                                        " METER=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].Channel[l].MeterID.ToString()) + "," +
                                                        " NPATS_ID=" + "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].Channel[l].ExportNPATSCode) + "'" + "," +
                                                        " NPATS_ID_IMP=" + "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].Channel[l].ImportNPATSCode) + "'" + "," +
                                                        " TYPE63002=" + "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].Channel[l].Value63002Code) + "'" + "," +
                                                        " ASKP_ID=" + "'" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].Channel[l].ASKPIdentifier) + "'" +//Проверить
                                                        " where DCID=" + FixIdentifierName(cMain.Objects[i].DCID.ToString()) +
                                                        " and OBJID=" + FixIdentifierName(cMain.Objects[i].ID.ToString()) +
                                                        " and DEVID=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].DeviceID.ToString()) +
                                                        " and JOINID=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].ID.ToString()) +
                                                        " and CHANID=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].Channel[l].ID.ToString());                                              

                                                    if (DbCommand.ExecuteNonQuery() > 0)
                                                        cMain.Objects[i].Device[j].Join[k].Channel[l].ItemAction.Changed = false;
                                                    AddToProgress(1);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Result = false;
                    MessageBox.Show(DbCommand.CommandText + e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return Result;
        }
        //Обновление в БД линий электропередач для присоединений
        public static Boolean UpdateJoinConnectionLines()
        {
            OleDbCommand DbCommand = null;
            Boolean Result = true;
            Int32 i, j, k, l;

            if (DbConnect != null)
            {
                try
                {
                    DbCommand = DbConnect.CreateCommand();
                    //Обновление линий электропередач для присоединений
                    for (i = 0; i < cMain.Objects.Length; i++)
                    {
                        if ((cMain.Objects[i].ItemAction.DBExist) &&
                            (!cMain.Objects[i].ItemAction.Deleted))
                        {
                            for (j = 0; j < cMain.Objects[i].Device.Length; j++)
                            {
                                if ((cMain.Objects[i].Device[j].ItemAction.DBExist) &&
                                    (!cMain.Objects[i].Device[j].ItemAction.Deleted))
                                {
                                    for (k = 0; k < cMain.Objects[i].Device[j].Join.Length; k++)
                                    {
                                        if ((cMain.Objects[i].Device[j].Join[k].ItemAction.DBExist) &&
                                            (!cMain.Objects[i].Device[j].Join[k].ItemAction.Deleted))
                                        {
                                            for (l = 0; l < cMain.Objects[i].Device[j].Join[k].ConnLineLosts.Length; l++)
                                            {
                                                if ((cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ItemAction.DBExist) &&
                                                    (cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ItemAction.Changed) &&
                                                    (!cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ItemAction.Deleted))
                                                {
                                                    DbCommand.CommandText =
                                                        "update LINES set" +                                                                                                         
                                                        " LENGTH=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].LineLength.ToString().Replace(",", ".")) + "," +
                                                        " RESISTIVITY=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].Resistance.ToString().Replace(",", ".")) + "," +
                                                        " VOLTAGE=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].UNominal.ToString().Replace(",", ".")) + "," +                                                        
                                                        " LOSS_UD_INSN=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].CableLost.ToString().Replace(",", ".")) + "," +
                                                        " LOSS_UD_INSR=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].AirLost.ToString().Replace(",", ".")) + "," +
                                                        " CIRCUITS_AMOUNT =" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].CircuitsAmount.ToString()) +
                                                        " where JOININC=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].Index.ToString()) +
                                                        " and LINEID=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ID.ToString());

                                                    if (DbCommand.ExecuteNonQuery() > 0)
                                                        cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ItemAction.Changed = false;
                                                    AddToProgress(1);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Result = false;
                    MessageBox.Show(DbCommand.CommandText + e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return Result;
        }
        //Обновление в БД групп отчетов для присоединений
        public static Boolean UpdateJoinReportGroups()
        {
            OleDbCommand DbCommand = null;
            Boolean Result = true;
            Int32 i, j, k, l;

            if (DbConnect != null)
            {
                try
                {
                    DbCommand = DbConnect.CreateCommand();
                    //Обновление групп отчетов для присоединений
                    for (i = 0; i < cMain.Objects.Length; i++)
                    {
                        if ((cMain.Objects[i].ItemAction.DBExist) &&
                            (!cMain.Objects[i].ItemAction.Deleted))
                        {
                            for (j = 0; j < cMain.Objects[i].Device.Length; j++)
                            {
                                if ((cMain.Objects[i].Device[j].ItemAction.DBExist) &&
                                    (!cMain.Objects[i].Device[j].ItemAction.Deleted))
                                {
                                    for (k = 0; k < cMain.Objects[i].Device[j].Join.Length; k++)
                                    {
                                        if ((cMain.Objects[i].Device[j].Join[k].ItemAction.DBExist) &&
                                            (!cMain.Objects[i].Device[j].Join[k].ItemAction.Deleted))
                                        {
                                            for (l = 0; l < cMain.Objects[i].Device[j].Join[k].ReportGroup.Length; l++)
                                            {
                                                if ((cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ItemAction.DBExist) &&
                                                    (cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ItemAction.Changed) &&
                                                    (!cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ItemAction.Deleted))
                                                {
                                                    DbCommand.CommandText =
                                                        "update JOIN_GROUP set" +
                                                        " REPGROUP_REF=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].ReportGroup[l].RGType.ToString()) +
                                                        " where DCID=" + FixIdentifierName(cMain.Objects[i].DCID.ToString()) +
                                                        " and OBJID=" + FixIdentifierName(cMain.Objects[i].ID.ToString()) +
                                                        " and DEVID=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].DeviceID.ToString()) +
                                                        " and JOINID=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].ID.ToString()) +
                                                        " and REPGROUPID=" + FixIdentifierName(cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ID.ToString());
                                                    if (DbCommand.ExecuteNonQuery() > 0)
                                                    {
                                                        cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ItemAction.DBExist = true;
                                                        cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ItemAction.Changed = false;
                                                    }
                                                    AddToProgress(1);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Result = false;
                    MessageBox.Show(DbCommand.CommandText + e.Message, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return Result;
        }

        //Удаление структур в памяти отмеченных на удаление
        public static Boolean RefreshNetwork()
        {
            Boolean Result = true;

            try
            {
                RefreshDeviceTypeList();//Удаление структур из справочника типов устройств отмеченных на удаление
                RefreshCommChanList(); //Удаление структур из справочника каналов связи  отмеченных на удаление
                RefreshMeterList();//Удаление структур из справочника счетчиков отмеченных на удаление
                RefreshTariffList();//Удаление структур из справочника тарифов отмеченных на удаление
                RefreshUserList();//Удаление структур из справочника пользователей отмеченных на удаление
                RefreshObjects();//Удаление структур объектов учета отмеченных на удаление
                RefreshDC();//Удаление структур территориальных объединений отмеченных на удаление
            }
            catch (Exception )
            {
                Result = false;                    
            }                
            return Result;
        }
        //Удаление из массива справочника типов устройств структур отмеченных на удаление
        private static void RefreshDeviceTypeList()
        {
            Int32 i, j;
            cMain.DEVTYPE_SETTING[] tmpDevTypeList = new cMain.DEVTYPE_SETTING[0];
                        
            for (i = 0; i < cMain.DevTypeList.Length; i++)
            {
                if ((cMain.DevTypeList[i].ItemAction.DBExist) ||
                    ((!cMain.DevTypeList[i].ItemAction.DBExist) && (!cMain.DevTypeList[i].ItemAction.Deleted)))
                {
                    Array.Resize(ref tmpDevTypeList, tmpDevTypeList.Length + 1);
                    tmpDevTypeList[tmpDevTypeList.Length - 1].ItemAction.DBExist = cMain.DevTypeList[i].ItemAction.DBExist;                        
                    tmpDevTypeList[tmpDevTypeList.Length - 1].ItemAction.Changed = cMain.DevTypeList[i].ItemAction.Changed;
                    tmpDevTypeList[tmpDevTypeList.Length - 1].ItemAction.Deleted = cMain.DevTypeList[i].ItemAction.Deleted;
                    tmpDevTypeList[tmpDevTypeList.Length - 1].ID = cMain.DevTypeList[i].ID;
                    tmpDevTypeList[tmpDevTypeList.Length - 1].DeviceDllName = cMain.DevTypeList[i].DeviceDllName;
                    tmpDevTypeList[tmpDevTypeList.Length - 1].ProtocolDLLName = cMain.DevTypeList[i].ProtocolDLLName;
                    tmpDevTypeList[tmpDevTypeList.Length - 1].Caption = cMain.DevTypeList[i].Caption;
                    tmpDevTypeList[tmpDevTypeList.Length - 1].DeviceKind = cMain.DevTypeList[i].DeviceKind;
                    tmpDevTypeList[tmpDevTypeList.Length - 1].ChannelCount = cMain.DevTypeList[i].ChannelCount;
                    tmpDevTypeList[tmpDevTypeList.Length - 1].FileCodeNPATS = cMain.DevTypeList[i].FileCodeNPATS;
                    tmpDevTypeList[tmpDevTypeList.Length - 1].ProtocolSetting = new Byte[cMain.DevTypeList[i].ProtocolSetting.Length];
                    for (j = 0; j < tmpDevTypeList[tmpDevTypeList.Length - 1].ProtocolSetting.Length; j++)
                        tmpDevTypeList[tmpDevTypeList.Length - 1].ProtocolSetting[j] = cMain.DevTypeList[i].ProtocolSetting[j];
                }
            }
            cMain.DevTypeList = new cMain.DEVTYPE_SETTING[tmpDevTypeList.Length];
            for (i = 0; i < cMain.DevTypeList.Length; i++)
            {
                cMain.DevTypeList[i].ItemAction.DBExist = tmpDevTypeList[i].ItemAction.DBExist;
                cMain.DevTypeList[i].ItemAction.Changed = tmpDevTypeList[i].ItemAction.Changed;
                cMain.DevTypeList[i].ItemAction.Deleted = tmpDevTypeList[i].ItemAction.Deleted;
                cMain.DevTypeList[i].ID = tmpDevTypeList[i].ID;
                cMain.DevTypeList[i].DeviceDllName = tmpDevTypeList[i].DeviceDllName;
                cMain.DevTypeList[i].ProtocolDLLName = tmpDevTypeList[i].ProtocolDLLName;
                cMain.DevTypeList[i].Caption = tmpDevTypeList[i].Caption;
                cMain.DevTypeList[i].DeviceKind = tmpDevTypeList[i].DeviceKind;
                cMain.DevTypeList[i].ChannelCount = tmpDevTypeList[i].ChannelCount;
                cMain.DevTypeList[i].FileCodeNPATS = tmpDevTypeList[i].FileCodeNPATS;
                cMain.DevTypeList[i].ProtocolSetting = new Byte[tmpDevTypeList[i].ProtocolSetting.Length];
                for (j = 0; j < cMain.DevTypeList[i].ProtocolSetting.Length; j++)
                    cMain.DevTypeList[i].ProtocolSetting[j] = tmpDevTypeList[i].ProtocolSetting[j];
            }
            tmpDevTypeList = new cMain.DEVTYPE_SETTING[0];
        }
        //Удаление из массива справочника каналов связи структур отмеченных на удаление
        private static void RefreshCommChanList()
        {
            Int32 i, j;
            cMain.COMMCHAN_SETTING[] tmpCommChanList = new cMain.COMMCHAN_SETTING[0];

            //Удаление ненужных структур из справочника каналов связи 
            for (i = 0; i < cMain.CommChanList.Length; i++)
            {
                if ((cMain.CommChanList[i].ItemAction.DBExist) ||
                    ((!cMain.CommChanList[i].ItemAction.DBExist) && (!cMain.CommChanList[i].ItemAction.Deleted)))
                {
                    Array.Resize(ref tmpCommChanList, tmpCommChanList.Length + 1);
                    tmpCommChanList[tmpCommChanList.Length - 1].ItemAction.DBExist = cMain.CommChanList[i].ItemAction.DBExist;
                    tmpCommChanList[tmpCommChanList.Length - 1].ItemAction.Changed = cMain.CommChanList[i].ItemAction.Changed;
                    tmpCommChanList[tmpCommChanList.Length - 1].ItemAction.Deleted = cMain.CommChanList[i].ItemAction.Deleted;
                    tmpCommChanList[tmpCommChanList.Length - 1].ID = cMain.CommChanList[i].ID;
                    tmpCommChanList[tmpCommChanList.Length - 1].DllName = cMain.CommChanList[i].DllName;
                    tmpCommChanList[tmpCommChanList.Length - 1].Caption = cMain.CommChanList[i].Caption;
                    tmpCommChanList[tmpCommChanList.Length - 1].GroupID = cMain.CommChanList[i].GroupID;

                    tmpCommChanList[tmpCommChanList.Length - 1].Setting = new Byte[cMain.CommChanList[i].Setting.Length];
                    for (j = 0; j < tmpCommChanList[tmpCommChanList.Length - 1].Setting.Length; j++)
                        tmpCommChanList[tmpCommChanList.Length - 1].Setting[j] = cMain.CommChanList[i].Setting[j];
                }
            }
            cMain.CommChanList = new cMain.COMMCHAN_SETTING[tmpCommChanList.Length];
            for (i = 0; i < cMain.CommChanList.Length; i++)
            {
                cMain.CommChanList[i].ItemAction.DBExist = tmpCommChanList[i].ItemAction.DBExist;
                cMain.CommChanList[i].ItemAction.Changed = tmpCommChanList[i].ItemAction.Changed;
                cMain.CommChanList[i].ItemAction.Deleted = tmpCommChanList[i].ItemAction.Deleted;
                cMain.CommChanList[i].ID = tmpCommChanList[i].ID;
                cMain.CommChanList[i].DllName = tmpCommChanList[i].DllName;
                cMain.CommChanList[i].Caption = tmpCommChanList[i].Caption;
                cMain.CommChanList[i].GroupID = tmpCommChanList[i].GroupID;

                cMain.CommChanList[i].Setting = new Byte[tmpCommChanList[i].Setting.Length];
                for (j = 0; j < cMain.CommChanList[i].Setting.Length; j++)
                    cMain.CommChanList[i].Setting[j] = tmpCommChanList[i].Setting[j];
            }
            tmpCommChanList = new cMain.COMMCHAN_SETTING[0];
        }
        //Удаление из массива справочника счетчиков структур отмеченных на удаление
        private static void RefreshMeterList()
        {
            Int32 i;
            cMain.METER_SETTING[] tmpMeterList = new cMain.METER_SETTING[0];
            
            for (i = 0; i < cMain.MeterList.Length; i++)
            {
                if ((cMain.MeterList[i].ItemAction.DBExist) ||
                    ((!cMain.MeterList[i].ItemAction.DBExist) && (!cMain.MeterList[i].ItemAction.Deleted)))
                {
                    Array.Resize(ref tmpMeterList, tmpMeterList.Length + 1);
                    tmpMeterList[tmpMeterList.Length - 1].ItemAction.DBExist = cMain.MeterList[i].ItemAction.DBExist;
                    tmpMeterList[tmpMeterList.Length - 1].ItemAction.Changed = cMain.MeterList[i].ItemAction.Changed;
                    tmpMeterList[tmpMeterList.Length - 1].ItemAction.Deleted = cMain.MeterList[i].ItemAction.Deleted;
                    tmpMeterList[tmpMeterList.Length - 1].ID = cMain.MeterList[i].ID;
                    tmpMeterList[tmpMeterList.Length - 1].Caption = cMain.MeterList[i].Caption;
                    tmpMeterList[tmpMeterList.Length - 1].Precision = cMain.MeterList[i].Precision;
                    tmpMeterList[tmpMeterList.Length - 1].BeforeComma = cMain.MeterList[i].BeforeComma;
                    tmpMeterList[tmpMeterList.Length - 1].AfterComma = cMain.MeterList[i].AfterComma;
                    tmpMeterList[tmpMeterList.Length - 1].MeterConst = cMain.MeterList[i].MeterConst;
                    tmpMeterList[tmpMeterList.Length - 1].Phase = cMain.MeterList[i].Phase;
                    tmpMeterList[tmpMeterList.Length - 1].SelfDemand = cMain.MeterList[i].SelfDemand;                    
                }
            }
            cMain.MeterList = new cMain.METER_SETTING[tmpMeterList.Length];
            for (i = 0; i < cMain.MeterList.Length; i++)
            {
                cMain.MeterList[i].ItemAction.DBExist = tmpMeterList[i].ItemAction.DBExist;
                cMain.MeterList[i].ItemAction.Changed = tmpMeterList[i].ItemAction.Changed;
                cMain.MeterList[i].ItemAction.Deleted = tmpMeterList[i].ItemAction.Deleted;
                cMain.MeterList[i].ID = tmpMeterList[i].ID;
                cMain.MeterList[i].Caption = tmpMeterList[i].Caption;
                cMain.MeterList[i].Precision = tmpMeterList[i].Precision;
                cMain.MeterList[i].BeforeComma = tmpMeterList[i].BeforeComma;
                cMain.MeterList[i].AfterComma = tmpMeterList[i].AfterComma;
                cMain.MeterList[i].MeterConst = tmpMeterList[i].MeterConst;
                cMain.MeterList[i].Phase = tmpMeterList[i].Phase;
                cMain.MeterList[i].SelfDemand = tmpMeterList[i].SelfDemand;
            }
            tmpMeterList = new cMain.METER_SETTING[0];
        }
        //Удаление из массива справочника тарифов структур отмеченных на удаление
        private static void RefreshTariffList()
        {
            Int32 i;
            cMain.TARIFF_SETTING[] tmpTariffList = new cMain.TARIFF_SETTING[0];

            for (i = 0; i < cMain.TariffList.Length; i++)
            {
                if ((cMain.TariffList[i].ItemAction.DBExist) ||
                    ((!cMain.TariffList[i].ItemAction.DBExist) && (!cMain.TariffList[i].ItemAction.Deleted)))
                {
                    Array.Resize(ref tmpTariffList, tmpTariffList.Length + 1);
                    tmpTariffList[tmpTariffList.Length - 1].ItemAction.DBExist = cMain.TariffList[i].ItemAction.DBExist;
                    tmpTariffList[tmpTariffList.Length - 1].ItemAction.Changed = cMain.TariffList[i].ItemAction.Changed;
                    tmpTariffList[tmpTariffList.Length - 1].ItemAction.Deleted = cMain.TariffList[i].ItemAction.Deleted;
                    tmpTariffList[tmpTariffList.Length - 1].ID = cMain.TariffList[i].ID;
                    tmpTariffList[tmpTariffList.Length - 1].Caption = cMain.TariffList[i].Caption;
                    tmpTariffList[tmpTariffList.Length - 1].FillColor = cMain.TariffList[i].FillColor;
                }
            }
            cMain.TariffList = new cMain.TARIFF_SETTING[tmpTariffList.Length];
            for (i = 0; i < cMain.TariffList.Length; i++)
            {
                cMain.TariffList[i].ItemAction.DBExist = tmpTariffList[i].ItemAction.DBExist;
                cMain.TariffList[i].ItemAction.Changed = tmpTariffList[i].ItemAction.Changed;
                cMain.TariffList[i].ItemAction.Deleted = tmpTariffList[i].ItemAction.Deleted;
                cMain.TariffList[i].ID = tmpTariffList[i].ID;
                cMain.TariffList[i].Caption = tmpTariffList[i].Caption;
                cMain.TariffList[i].FillColor = tmpTariffList[i].FillColor;                
            }
            tmpTariffList = new cMain.TARIFF_SETTING[0];
        }
        //Удаление из массива пользователей структур отмеченных на удаление
        private static void RefreshUserList()
        {
            Int32 i;
            cMain.USER_SETTING[] tmpUserList = new cMain.USER_SETTING[0];

            for (i = 0; i < cMain.UserList.Length; i++)
            {
                if ((cMain.UserList[i].ItemAction.DBExist) ||
                    ((!cMain.UserList[i].ItemAction.DBExist) && (!cMain.UserList[i].ItemAction.Deleted)))
                {
                    Array.Resize(ref tmpUserList, tmpUserList.Length + 1);
                    tmpUserList[tmpUserList.Length - 1].ItemAction.DBExist = cMain.UserList[i].ItemAction.DBExist;
                    tmpUserList[tmpUserList.Length - 1].ItemAction.Changed = cMain.UserList[i].ItemAction.Changed;
                    tmpUserList[tmpUserList.Length - 1].ItemAction.Deleted = cMain.UserList[i].ItemAction.Deleted;
                    tmpUserList[tmpUserList.Length - 1].ID = cMain.UserList[i].ID;
                    tmpUserList[tmpUserList.Length - 1].Caption = cMain.UserList[i].Caption;
                    tmpUserList[tmpUserList.Length - 1].Password = cMain.UserList[i].Password;
                    tmpUserList[tmpUserList.Length - 1].AccessID = cMain.UserList[i].AccessID;
                }
            }
            cMain.UserList = new cMain.USER_SETTING[tmpUserList.Length];
            for (i = 0; i < cMain.UserList.Length; i++)
            {
                cMain.UserList[i].ItemAction.DBExist = tmpUserList[i].ItemAction.DBExist;
                cMain.UserList[i].ItemAction.Changed = tmpUserList[i].ItemAction.Changed;
                cMain.UserList[i].ItemAction.Deleted = tmpUserList[i].ItemAction.Deleted;
                cMain.UserList[i].ID = tmpUserList[i].ID;
                cMain.UserList[i].Caption = tmpUserList[i].Caption;
                cMain.UserList[i].Password = tmpUserList[i].Password;
                cMain.UserList[i].AccessID = tmpUserList[i].AccessID;
            }
            tmpUserList = new cMain.USER_SETTING[0];
        }
        //Удаление из массива объектов учета структур отмеченных на удаление
        private static void RefreshObjects()
        {
            Int32 i, j, k, l, ObjEndIdx, DevEndIdx, CEEndIdx, JoinEndIdx, EndIdx;
            cMain.OBJECT[] tmpObjects = new cMain.OBJECT[0];

            //Копирование только актуальных объектов учета
            for (i = 0; i < cMain.Objects.Length; i++)
            {
                if ((cMain.Objects[i].ItemAction.DBExist) ||
                    ((!cMain.Objects[i].ItemAction.DBExist) && (!cMain.Objects[i].ItemAction.Deleted)))
                {
                    ObjEndIdx = tmpObjects.Length;
                    Array.Resize(ref tmpObjects, ObjEndIdx + 1);
                    tmpObjects[ObjEndIdx].ItemAction.DBExist = cMain.Objects[i].ItemAction.DBExist;
                    tmpObjects[ObjEndIdx].ItemAction.Changed = cMain.Objects[i].ItemAction.Changed;
                    tmpObjects[ObjEndIdx].ItemAction.Deleted = cMain.Objects[i].ItemAction.Deleted;

                    tmpObjects[ObjEndIdx].DCID = cMain.Objects[i].DCID;
                    tmpObjects[ObjEndIdx].ID = cMain.Objects[i].ID;
                    tmpObjects[ObjEndIdx].Caption = cMain.Objects[i].Caption;
                    tmpObjects[ObjEndIdx].ComputerAddress = cMain.Objects[i].ComputerAddress;
                    tmpObjects[ObjEndIdx].CommChan = cMain.Objects[i].CommChan;
                    tmpObjects[ObjEndIdx].AddCommChan = cMain.Objects[i].AddCommChan;
                    tmpObjects[ObjEndIdx].CollectionState = cMain.Objects[i].CollectionState;
                    tmpObjects[ObjEndIdx].CollectionStartDT = cMain.Objects[i].CollectionStartDT;
                    tmpObjects[ObjEndIdx].tcPeriodType = cMain.Objects[i].tcPeriodType;
                    tmpObjects[ObjEndIdx].tcPeriodCount = cMain.Objects[i].tcPeriodCount;
                    tmpObjects[ObjEndIdx].Schedule = new cMain.SCHEDULE[cMain.Objects[i].Schedule.Length];
                    for (j = 0; j < tmpObjects[ObjEndIdx].Schedule.Length; j++)
                    {                                                
                        tmpObjects[ObjEndIdx].Schedule[j].ID = cMain.Objects[i].Schedule[j].ID;
                        tmpObjects[ObjEndIdx].Schedule[j].PeriodTypeID = cMain.Objects[i].Schedule[j].PeriodTypeID;
                        tmpObjects[ObjEndIdx].Schedule[j].PeriodCountID = cMain.Objects[i].Schedule[j].PeriodCountID;
                        tmpObjects[ObjEndIdx].Schedule[j].CollectOn = cMain.Objects[i].Schedule[j].CollectOn;
                        tmpObjects[ObjEndIdx].Schedule[j].CPeriodType = cMain.Objects[i].Schedule[j].CPeriodType;
                        tmpObjects[ObjEndIdx].Schedule[j].CPeriodCount = cMain.Objects[i].Schedule[j].CPeriodCount;
                        tmpObjects[ObjEndIdx].Schedule[j].DPeriodType = cMain.Objects[i].Schedule[j].DPeriodType;
                        tmpObjects[ObjEndIdx].Schedule[j].DPeriodCount = cMain.Objects[i].Schedule[j].DPeriodCount;
                        tmpObjects[ObjEndIdx].Schedule[j].HPeriodType = cMain.Objects[i].Schedule[j].HPeriodType;
                        tmpObjects[ObjEndIdx].Schedule[j].HPeriodCount = cMain.Objects[i].Schedule[j].HPeriodCount;
                    }
                    tmpObjects[ObjEndIdx].CodeNPATS = cMain.Objects[i].CodeNPATS;
                    tmpObjects[ObjEndIdx].Code63002 = cMain.Objects[i].Code63002;
                    tmpObjects[ObjEndIdx].IsExported = cMain.Objects[i].IsExported;
                    tmpObjects[ObjEndIdx].ExportDCID = cMain.Objects[i].ExportDCID;
                    tmpObjects[ObjEndIdx].ExportObjID = cMain.Objects[i].ExportObjID;

                    //Копирование только актуальных устройств
                    tmpObjects[ObjEndIdx].Device = new cMain.DEVICE[0];
                    for (j = 0; j < cMain.Objects[i].Device.Length; j++)
                    {
                        if ((cMain.Objects[i].Device[j].ItemAction.DBExist) ||
                            ((!cMain.Objects[i].Device[j].ItemAction.DBExist) && (!cMain.Objects[i].Device[j].ItemAction.Deleted)))
                        {
                            DevEndIdx = tmpObjects[ObjEndIdx].Device.Length;
                            Array.Resize(ref tmpObjects[ObjEndIdx].Device, DevEndIdx + 1);
                            tmpObjects[ObjEndIdx].Device[DevEndIdx].ItemAction.DBExist = cMain.Objects[i].Device[j].ItemAction.DBExist;
                            tmpObjects[ObjEndIdx].Device[DevEndIdx].ItemAction.Changed = cMain.Objects[i].Device[j].ItemAction.Changed;
                            tmpObjects[ObjEndIdx].Device[DevEndIdx].ItemAction.Deleted = cMain.Objects[i].Device[j].ItemAction.Deleted;

                            tmpObjects[ObjEndIdx].Device[DevEndIdx].ID = cMain.Objects[i].Device[j].ID;
                            tmpObjects[ObjEndIdx].Device[DevEndIdx].DeviceID = cMain.Objects[i].Device[j].DeviceID;
                            tmpObjects[ObjEndIdx].Device[DevEndIdx].NetAddress = cMain.Objects[i].Device[j].NetAddress;
                            tmpObjects[ObjEndIdx].Device[DevEndIdx].Address = cMain.Objects[i].Device[j].Address;
                            tmpObjects[ObjEndIdx].Device[DevEndIdx].Identifier = cMain.Objects[i].Device[j].Identifier;
                            tmpObjects[ObjEndIdx].Device[DevEndIdx].SerialNumber = cMain.Objects[i].Device[j].SerialNumber;
                            tmpObjects[ObjEndIdx].Device[DevEndIdx].JournalLastDT = cMain.Objects[i].Device[j].JournalLastDT;
                            tmpObjects[ObjEndIdx].Device[DevEndIdx].LastEventIdx = cMain.Objects[i].Device[j].LastEventIdx;
                            tmpObjects[ObjEndIdx].Device[DevEndIdx].IsExported = cMain.Objects[i].Device[j].IsExported;
                            tmpObjects[ObjEndIdx].Device[DevEndIdx].UserName = cMain.Objects[i].Device[j].UserName;
                            tmpObjects[ObjEndIdx].Device[DevEndIdx].UserPassword = cMain.Objects[i].Device[j].UserPassword;
                            tmpObjects[ObjEndIdx].Device[DevEndIdx].ProtocolSetting = new Byte[cMain.Objects[i].Device[j].ProtocolSetting.Length];
                            for (k = 0; k < tmpObjects[ObjEndIdx].Device[DevEndIdx].ProtocolSetting.Length; k++)
                                tmpObjects[ObjEndIdx].Device[DevEndIdx].ProtocolSetting[k] = cMain.Objects[i].Device[j].ProtocolSetting[k];

                            //Копирование только актуального коммуникационного оборудования устройства
                            tmpObjects[ObjEndIdx].Device[DevEndIdx].CommEquipment = new cMain.COMMUTATION_EQUIPMENT[0];
                            for (k = 0; k < cMain.Objects[i].Device[j].CommEquipment.Length; k++)
                            {
                                if ((cMain.Objects[i].Device[j].CommEquipment[k].ItemAction.DBExist) ||
                                    ((!cMain.Objects[i].Device[j].CommEquipment[k].ItemAction.DBExist) && (!cMain.Objects[i].Device[j].CommEquipment[k].ItemAction.Deleted)))
                                {
                                    CEEndIdx = tmpObjects[ObjEndIdx].Device[DevEndIdx].CommEquipment.Length;
                                    Array.Resize(ref tmpObjects[ObjEndIdx].Device[DevEndIdx].CommEquipment, CEEndIdx + 1);
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].CommEquipment[CEEndIdx].ItemAction.DBExist = cMain.Objects[i].Device[j].CommEquipment[k].ItemAction.DBExist;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].CommEquipment[CEEndIdx].ItemAction.Changed = cMain.Objects[i].Device[j].CommEquipment[k].ItemAction.Changed;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].CommEquipment[CEEndIdx].ItemAction.Deleted = cMain.Objects[i].Device[j].CommEquipment[k].ItemAction.Deleted;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].CommEquipment[CEEndIdx].ID = cMain.Objects[i].Device[j].CommEquipment[k].ID;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].CommEquipment[CEEndIdx].ChannelNumber = cMain.Objects[i].Device[j].CommEquipment[k].ChannelNumber;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].CommEquipment[CEEndIdx].Caption = cMain.Objects[i].Device[j].CommEquipment[k].Caption;
                                }
                            }

                            //Копирование только актуальных присоединений устройства
                            tmpObjects[ObjEndIdx].Device[DevEndIdx].Join = new cMain.JOIN[0];
                            for (k = 0; k < cMain.Objects[i].Device[j].Join.Length; k++)
                            {
                                if ((cMain.Objects[i].Device[j].Join[k].ItemAction.DBExist) ||
                                    ((!cMain.Objects[i].Device[j].Join[k].ItemAction.DBExist) && (!cMain.Objects[i].Device[j].Join[k].ItemAction.Deleted)))
                                {
                                    JoinEndIdx = tmpObjects[ObjEndIdx].Device[DevEndIdx].Join.Length;
                                    Array.Resize(ref tmpObjects[ObjEndIdx].Device[DevEndIdx].Join, JoinEndIdx + 1);

                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].ItemAction.DBExist = cMain.Objects[i].Device[j].Join[k].ItemAction.DBExist;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].ItemAction.Changed = cMain.Objects[i].Device[j].Join[k].ItemAction.Changed;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].ItemAction.Deleted = cMain.Objects[i].Device[j].Join[k].ItemAction.Deleted;                                    
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].DeviceID = cMain.Objects[i].Device[j].Join[k].DeviceID;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].ID = cMain.Objects[i].Device[j].Join[k].ID;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].Index = cMain.Objects[i].Device[j].Join[k].Index;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].Caption = cMain.Objects[i].Device[j].Join[k].Caption;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].MeterNumber = cMain.Objects[i].Device[j].Join[k].MeterNumber;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].CollectEnable = cMain.Objects[i].Device[j].Join[k].CollectEnable;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].CoeffMultiply = cMain.Objects[i].Device[j].Join[k].CoeffMultiply;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].ConvertParam = cMain.Objects[i].Device[j].Join[k].ConvertParam;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].KTT = cMain.Objects[i].Device[j].Join[k].KTT;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].KTN = cMain.Objects[i].Device[j].Join[k].KTN;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].KTTClass = cMain.Objects[i].Device[j].Join[k].KTTClass;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].KTNClass = cMain.Objects[i].Device[j].Join[k].KTNClass;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].IdlingLosts = cMain.Objects[i].Device[j].Join[k].IdlingLosts;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].ShortCircuitLosts = cMain.Objects[i].Device[j].Join[k].ShortCircuitLosts;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].TransformatorPower = cMain.Objects[i].Device[j].Join[k].TransformatorPower;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].MeterLostsValue = cMain.Objects[i].Device[j].Join[k].MeterLostsValue;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].TTLostsValue = cMain.Objects[i].Device[j].Join[k].TTLostsValue;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].TNLostsValue = cMain.Objects[i].Device[j].Join[k].TNLostsValue;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].MeterCodeHPATS = cMain.Objects[i].Device[j].Join[k].MeterCodeHPATS;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].ExportCodeHPATS = cMain.Objects[i].Device[j].Join[k].ExportCodeHPATS;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].ImportCodeHPATS = cMain.Objects[i].Device[j].Join[k].ImportCodeHPATS;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].CollectPointAddress = cMain.Objects[i].Device[j].Join[k].CollectPointAddress;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].MeterPlacement = cMain.Objects[i].Device[j].Join[k].MeterPlacement;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].Comments = cMain.Objects[i].Device[j].Join[k].Comments;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].AbonentNumber = cMain.Objects[i].Device[j].Join[k].AbonentNumber;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].AgreementNumber = cMain.Objects[i].Device[j].Join[k].AgreementNumber;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].EvidenceMetod = cMain.Objects[i].Device[j].Join[k].EvidenceMetod;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].BalanceBelonging = cMain.Objects[i].Device[j].Join[k].BalanceBelonging;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].Director = cMain.Objects[i].Device[j].Join[k].Director;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].GeneralPES = cMain.Objects[i].Device[j].Join[k].GeneralPES;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].PhoneNumber = cMain.Objects[i].Device[j].Join[k].PhoneNumber;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].DTLastInspection = cMain.Objects[i].Device[j].Join[k].DTLastInspection;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].InSubscriberGroup = cMain.Objects[i].Device[j].Join[k].InSubscriberGroup;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].KPE = cMain.Objects[i].Device[j].Join[k].KPE;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].KPM = cMain.Objects[i].Device[j].Join[k].KPM;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].UTariffLevel = cMain.Objects[i].Device[j].Join[k].UTariffLevel;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].UTransformator = cMain.Objects[i].Device[j].Join[k].UTransformator;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].TransformatorLosts = cMain.Objects[i].Device[j].Join[k].TransformatorLosts;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].LineLosts = cMain.Objects[i].Device[j].Join[k].LineLosts;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].ITransformatorType = cMain.Objects[i].Device[j].Join[k].ITransformatorType;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].INominalFirstTT = cMain.Objects[i].Device[j].Join[k].INominalFirstTT;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].INominalSecondTT = cMain.Objects[i].Device[j].Join[k].INominalSecondTT;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].UTransformatorType = cMain.Objects[i].Device[j].Join[k].UTransformatorType;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].UNominalFirstTT = cMain.Objects[i].Device[j].Join[k].UNominalFirstTT;
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].UNominalSecondTT = cMain.Objects[i].Device[j].Join[k].UNominalSecondTT;

                                    //Копирование только актуальных каналов учета присоединения
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].Channel = new cMain.CHANNEL[0];
                                    for (l = 0; l < cMain.Objects[i].Device[j].Join[k].Channel.Length; l++)
                                    {
                                        if ((cMain.Objects[i].Device[j].Join[k].Channel[l].ItemAction.DBExist) ||
                                            ((!cMain.Objects[i].Device[j].Join[k].Channel[l].ItemAction.DBExist) && (!cMain.Objects[i].Device[j].Join[k].Channel[l].ItemAction.Deleted)))
                                        {
                                            EndIdx = tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].Channel.Length;
                                            Array.Resize(ref tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].Channel, EndIdx + 1);

                                            tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].Channel[EndIdx].ItemAction.DBExist = cMain.Objects[i].Device[j].Join[k].Channel[l].ItemAction.DBExist;
                                            tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].Channel[EndIdx].ItemAction.Changed = cMain.Objects[i].Device[j].Join[k].Channel[l].ItemAction.Changed;
                                            tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].Channel[EndIdx].ItemAction.Deleted = cMain.Objects[i].Device[j].Join[k].Channel[l].ItemAction.Deleted;
                                            tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].Channel[EndIdx].ID = cMain.Objects[i].Device[j].Join[k].Channel[l].ID;
                                            tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].Channel[EndIdx].CollectEnable = cMain.Objects[i].Device[j].Join[k].Channel[l].CollectEnable;
                                            tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].Channel[EndIdx].EnergyType = cMain.Objects[i].Device[j].Join[k].Channel[l].EnergyType;
                                            tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].Channel[EndIdx].MeterSerial = cMain.Objects[i].Device[j].Join[k].Channel[l].MeterSerial;
                                            tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].Channel[EndIdx].MeterID = cMain.Objects[i].Device[j].Join[k].Channel[l].MeterID;
                                            tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].Channel[EndIdx].ExportNPATSCode = cMain.Objects[i].Device[j].Join[k].Channel[l].ExportNPATSCode;
                                            tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].Channel[EndIdx].ImportNPATSCode = cMain.Objects[i].Device[j].Join[k].Channel[l].ImportNPATSCode;
                                            tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].Channel[EndIdx].Value63002Code = cMain.Objects[i].Device[j].Join[k].Channel[l].Value63002Code;
                                            tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].Channel[EndIdx].ASKPIdentifier = cMain.Objects[i].Device[j].Join[k].Channel[l].ASKPIdentifier;
                                        }
                                    }
                                    //Копирование только актуальных линий электропередач присоединения
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].ConnLineLosts = new cMain.CONN_LINE_LOSTS[0];
                                    for (l = 0; l < cMain.Objects[i].Device[j].Join[k].ConnLineLosts.Length; l++)
                                    {
                                        if ((cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ItemAction.DBExist) ||
                                            ((!cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ItemAction.DBExist) && (!cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ItemAction.Deleted)))
                                        {
                                            EndIdx = tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].ConnLineLosts.Length;
                                            Array.Resize(ref tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].ConnLineLosts, EndIdx + 1);

                                            tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].ConnLineLosts[EndIdx].ItemAction.DBExist = cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ItemAction.DBExist;
                                            tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].ConnLineLosts[EndIdx].ItemAction.Changed = cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ItemAction.Changed;
                                            tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].ConnLineLosts[EndIdx].ItemAction.Deleted = cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ItemAction.Deleted;
                                            tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].ConnLineLosts[EndIdx].ID = cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ID;
                                            tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].ConnLineLosts[EndIdx].LineLength = cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].LineLength;
                                            tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].ConnLineLosts[EndIdx].Resistance = cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].Resistance;
                                            tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].ConnLineLosts[EndIdx].UNominal = cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].UNominal;
                                            tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].ConnLineLosts[EndIdx].CableLost = cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].CableLost;
                                            tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].ConnLineLosts[EndIdx].AirLost = cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].AirLost;
                                            tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].ConnLineLosts[EndIdx].CircuitsAmount = cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].CircuitsAmount;                                                
                                        }
                                    }
                                    //Копирование только актуальных групп отчетов присоединения
                                    tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].ReportGroup = new cMain.REPORT_GROUP[0];
                                    for (l = 0; l < cMain.Objects[i].Device[j].Join[k].ReportGroup.Length; l++)
                                    {
                                        if ((cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ItemAction.DBExist) ||
                                            ((!cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ItemAction.DBExist) && (!cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ItemAction.Deleted)))
                                        {
                                            EndIdx = tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].ReportGroup.Length;
                                            Array.Resize(ref tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].ReportGroup, EndIdx + 1);

                                            tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].ReportGroup[EndIdx].ItemAction.DBExist = cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ItemAction.DBExist;
                                            tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].ReportGroup[EndIdx].ItemAction.Changed = cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ItemAction.Changed;
                                            tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].ReportGroup[EndIdx].ItemAction.Deleted = cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ItemAction.Deleted;
                                            tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].ReportGroup[EndIdx].ID = cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ID;
                                            tmpObjects[ObjEndIdx].Device[DevEndIdx].Join[JoinEndIdx].ReportGroup[EndIdx].RGType = cMain.Objects[i].Device[j].Join[k].ReportGroup[l].RGType;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            //Копирование объектов учета
            cMain.Objects = new cMain.OBJECT[0];
            cMain.Objects = new cMain.OBJECT[tmpObjects.Length];            
            for (i = 0; i < cMain.Objects.Length; i++)
            {
                cMain.Objects[i].ItemAction.DBExist = tmpObjects[i].ItemAction.DBExist;
                cMain.Objects[i].ItemAction.Changed = tmpObjects[i].ItemAction.Changed;
                cMain.Objects[i].ItemAction.Deleted = tmpObjects[i].ItemAction.Deleted;

                cMain.Objects[i].DCID = tmpObjects[i].DCID;
                cMain.Objects[i].ID = tmpObjects[i].ID;
                cMain.Objects[i].Caption = tmpObjects[i].Caption;
                cMain.Objects[i].ComputerAddress = tmpObjects[i].ComputerAddress;
                cMain.Objects[i].CommChan = tmpObjects[i].CommChan;
                cMain.Objects[i].AddCommChan = tmpObjects[i].AddCommChan;
                cMain.Objects[i].CollectionState = tmpObjects[i].CollectionState;
                cMain.Objects[i].CollectionStartDT = tmpObjects[i].CollectionStartDT;
                cMain.Objects[i].tcPeriodType = tmpObjects[i].tcPeriodType;
                cMain.Objects[i].tcPeriodCount = tmpObjects[i].tcPeriodCount;
                cMain.Objects[i].Schedule = new cMain.SCHEDULE[tmpObjects[i].Schedule.Length];
                for (j = 0; j < cMain.Objects[i].Schedule.Length; j++)
                {
                    cMain.Objects[i].Schedule[j].ID = tmpObjects[i].Schedule[j].ID;
                    cMain.Objects[i].Schedule[j].PeriodTypeID = tmpObjects[i].Schedule[j].PeriodTypeID;
                    cMain.Objects[i].Schedule[j].PeriodCountID = tmpObjects[i].Schedule[j].PeriodCountID;
                    cMain.Objects[i].Schedule[j].CollectOn = tmpObjects[i].Schedule[j].CollectOn;
                    cMain.Objects[i].Schedule[j].CPeriodType = tmpObjects[i].Schedule[j].CPeriodType;
                    cMain.Objects[i].Schedule[j].CPeriodCount = tmpObjects[i].Schedule[j].CPeriodCount;
                    cMain.Objects[i].Schedule[j].DPeriodType = tmpObjects[i].Schedule[j].DPeriodType;
                    cMain.Objects[i].Schedule[j].DPeriodCount = tmpObjects[i].Schedule[j].DPeriodCount;
                    cMain.Objects[i].Schedule[j].HPeriodType = tmpObjects[i].Schedule[j].HPeriodType;
                    cMain.Objects[i].Schedule[j].HPeriodCount = tmpObjects[i].Schedule[j].HPeriodCount;
                }
                cMain.Objects[i].CodeNPATS = tmpObjects[i].CodeNPATS;
                cMain.Objects[i].Code63002 = tmpObjects[i].Code63002;
                cMain.Objects[i].IsExported = tmpObjects[i].IsExported;
                cMain.Objects[i].ExportDCID = tmpObjects[i].ExportDCID;
                cMain.Objects[i].ExportObjID = tmpObjects[i].ExportObjID;

                //Копирование устройств                
                cMain.Objects[i].Device = new cMain.DEVICE[tmpObjects[i].Device.Length];
                for (j = 0; j < cMain.Objects[i].Device.Length; j++)
                {
                    cMain.Objects[i].Device[j].ItemAction.DBExist = tmpObjects[i].Device[j].ItemAction.DBExist;
                    cMain.Objects[i].Device[j].ItemAction.Changed = tmpObjects[i].Device[j].ItemAction.Changed;
                    cMain.Objects[i].Device[j].ItemAction.Deleted = tmpObjects[i].Device[j].ItemAction.Deleted;

                    cMain.Objects[i].Device[j].ID = tmpObjects[i].Device[j].ID;
                    cMain.Objects[i].Device[j].DeviceID = tmpObjects[i].Device[j].DeviceID;
                    cMain.Objects[i].Device[j].NetAddress = tmpObjects[i].Device[j].NetAddress;
                    cMain.Objects[i].Device[j].Address = tmpObjects[i].Device[j].Address;
                    cMain.Objects[i].Device[j].Identifier = tmpObjects[i].Device[j].Identifier;
                    cMain.Objects[i].Device[j].SerialNumber = tmpObjects[i].Device[j].SerialNumber;
                    cMain.Objects[i].Device[j].JournalLastDT = tmpObjects[i].Device[j].JournalLastDT;
                    cMain.Objects[i].Device[j].LastEventIdx = tmpObjects[i].Device[j].LastEventIdx;
                    cMain.Objects[i].Device[j].IsExported = tmpObjects[i].Device[j].IsExported;
                    cMain.Objects[i].Device[j].UserName = tmpObjects[i].Device[j].UserName;
                    cMain.Objects[i].Device[j].UserPassword = tmpObjects[i].Device[j].UserPassword;
                    cMain.Objects[i].Device[j].ProtocolSetting = new Byte[tmpObjects[i].Device[j].ProtocolSetting.Length];
                    for (k = 0; k < cMain.Objects[i].Device[j].ProtocolSetting.Length; k++)
                        cMain.Objects[i].Device[j].ProtocolSetting[k] = tmpObjects[i].Device[j].ProtocolSetting[k];
                    
                    //Копирование коммуникационного оборудования устройства
                    cMain.Objects[i].Device[j].CommEquipment = new cMain.COMMUTATION_EQUIPMENT[tmpObjects[i].Device[j].CommEquipment.Length];
                    for (k = 0; k < cMain.Objects[i].Device[j].CommEquipment.Length; k++)
                    {
                        cMain.Objects[i].Device[j].CommEquipment[k].ItemAction.DBExist = tmpObjects[i].Device[j].CommEquipment[k].ItemAction.DBExist;
                        cMain.Objects[i].Device[j].CommEquipment[k].ItemAction.Changed = tmpObjects[i].Device[j].CommEquipment[k].ItemAction.Changed;
                        cMain.Objects[i].Device[j].CommEquipment[k].ItemAction.Deleted = tmpObjects[i].Device[j].CommEquipment[k].ItemAction.Deleted;
                        cMain.Objects[i].Device[j].CommEquipment[k].ID = tmpObjects[i].Device[j].CommEquipment[k].ID;
                        cMain.Objects[i].Device[j].CommEquipment[k].ChannelNumber = tmpObjects[i].Device[j].CommEquipment[k].ChannelNumber;
                        cMain.Objects[i].Device[j].CommEquipment[k].Caption = tmpObjects[i].Device[j].CommEquipment[k].Caption;
                    }

                    //Копирование присоединений устройства
                    cMain.Objects[i].Device[j].Join = new cMain.JOIN[tmpObjects[i].Device[j].Join.Length];
                    for (k = 0; k < cMain.Objects[i].Device[j].Join.Length; k++)
                    {
                        cMain.Objects[i].Device[j].Join[k].ItemAction.DBExist = tmpObjects[i].Device[j].Join[k].ItemAction.DBExist;
                        cMain.Objects[i].Device[j].Join[k].ItemAction.Changed = tmpObjects[i].Device[j].Join[k].ItemAction.Changed;
                        cMain.Objects[i].Device[j].Join[k].ItemAction.Deleted = tmpObjects[i].Device[j].Join[k].ItemAction.Deleted;
                        cMain.Objects[i].Device[j].Join[k].DeviceID = tmpObjects[i].Device[j].Join[k].DeviceID;
                        cMain.Objects[i].Device[j].Join[k].ID = tmpObjects[i].Device[j].Join[k].ID;
                        cMain.Objects[i].Device[j].Join[k].Index = tmpObjects[i].Device[j].Join[k].Index;
                        cMain.Objects[i].Device[j].Join[k].Caption = tmpObjects[i].Device[j].Join[k].Caption;
                        cMain.Objects[i].Device[j].Join[k].MeterNumber = tmpObjects[i].Device[j].Join[k].MeterNumber;
                        cMain.Objects[i].Device[j].Join[k].CollectEnable = tmpObjects[i].Device[j].Join[k].CollectEnable;
                        cMain.Objects[i].Device[j].Join[k].CoeffMultiply = tmpObjects[i].Device[j].Join[k].CoeffMultiply;
                        cMain.Objects[i].Device[j].Join[k].ConvertParam = tmpObjects[i].Device[j].Join[k].ConvertParam;
                        cMain.Objects[i].Device[j].Join[k].KTT = tmpObjects[i].Device[j].Join[k].KTT;
                        cMain.Objects[i].Device[j].Join[k].KTN = tmpObjects[i].Device[j].Join[k].KTN;
                        cMain.Objects[i].Device[j].Join[k].KTTClass = tmpObjects[i].Device[j].Join[k].KTTClass;
                        cMain.Objects[i].Device[j].Join[k].KTNClass = tmpObjects[i].Device[j].Join[k].KTNClass;
                        cMain.Objects[i].Device[j].Join[k].IdlingLosts = tmpObjects[i].Device[j].Join[k].IdlingLosts;
                        cMain.Objects[i].Device[j].Join[k].ShortCircuitLosts = tmpObjects[i].Device[j].Join[k].ShortCircuitLosts;
                        cMain.Objects[i].Device[j].Join[k].TransformatorPower = tmpObjects[i].Device[j].Join[k].TransformatorPower;
                        cMain.Objects[i].Device[j].Join[k].MeterLostsValue = tmpObjects[i].Device[j].Join[k].MeterLostsValue;
                        cMain.Objects[i].Device[j].Join[k].TTLostsValue = tmpObjects[i].Device[j].Join[k].TTLostsValue;
                        cMain.Objects[i].Device[j].Join[k].TNLostsValue = tmpObjects[i].Device[j].Join[k].TNLostsValue;
                        cMain.Objects[i].Device[j].Join[k].MeterCodeHPATS = tmpObjects[i].Device[j].Join[k].MeterCodeHPATS;
                        cMain.Objects[i].Device[j].Join[k].ExportCodeHPATS = tmpObjects[i].Device[j].Join[k].ExportCodeHPATS;
                        cMain.Objects[i].Device[j].Join[k].ImportCodeHPATS = tmpObjects[i].Device[j].Join[k].ImportCodeHPATS;
                        cMain.Objects[i].Device[j].Join[k].CollectPointAddress = tmpObjects[i].Device[j].Join[k].CollectPointAddress;
                        cMain.Objects[i].Device[j].Join[k].MeterPlacement = tmpObjects[i].Device[j].Join[k].MeterPlacement;
                        cMain.Objects[i].Device[j].Join[k].Comments = tmpObjects[i].Device[j].Join[k].Comments;
                        cMain.Objects[i].Device[j].Join[k].AbonentNumber = tmpObjects[i].Device[j].Join[k].AbonentNumber;
                        cMain.Objects[i].Device[j].Join[k].AgreementNumber = tmpObjects[i].Device[j].Join[k].AgreementNumber;
                        cMain.Objects[i].Device[j].Join[k].EvidenceMetod = tmpObjects[i].Device[j].Join[k].EvidenceMetod;
                        cMain.Objects[i].Device[j].Join[k].BalanceBelonging = tmpObjects[i].Device[j].Join[k].BalanceBelonging;
                        cMain.Objects[i].Device[j].Join[k].Director = tmpObjects[i].Device[j].Join[k].Director;
                        cMain.Objects[i].Device[j].Join[k].GeneralPES = tmpObjects[i].Device[j].Join[k].GeneralPES;
                        cMain.Objects[i].Device[j].Join[k].PhoneNumber = tmpObjects[i].Device[j].Join[k].PhoneNumber;
                        cMain.Objects[i].Device[j].Join[k].DTLastInspection = tmpObjects[i].Device[j].Join[k].DTLastInspection;
                        cMain.Objects[i].Device[j].Join[k].InSubscriberGroup = tmpObjects[i].Device[j].Join[k].InSubscriberGroup;
                        cMain.Objects[i].Device[j].Join[k].KPE = tmpObjects[i].Device[j].Join[k].KPE;
                        cMain.Objects[i].Device[j].Join[k].KPM = tmpObjects[i].Device[j].Join[k].KPM;
                        cMain.Objects[i].Device[j].Join[k].UTariffLevel = tmpObjects[i].Device[j].Join[k].UTariffLevel;
                        cMain.Objects[i].Device[j].Join[k].UTransformator = tmpObjects[i].Device[j].Join[k].UTransformator;
                        cMain.Objects[i].Device[j].Join[k].TransformatorLosts = tmpObjects[i].Device[j].Join[k].TransformatorLosts;
                        cMain.Objects[i].Device[j].Join[k].LineLosts = tmpObjects[i].Device[j].Join[k].LineLosts;
                        cMain.Objects[i].Device[j].Join[k].ITransformatorType = tmpObjects[i].Device[j].Join[k].ITransformatorType;
                        cMain.Objects[i].Device[j].Join[k].INominalFirstTT = tmpObjects[i].Device[j].Join[k].INominalFirstTT;
                        cMain.Objects[i].Device[j].Join[k].INominalSecondTT = tmpObjects[i].Device[j].Join[k].INominalSecondTT;
                        cMain.Objects[i].Device[j].Join[k].UTransformatorType = tmpObjects[i].Device[j].Join[k].UTransformatorType;
                        cMain.Objects[i].Device[j].Join[k].UNominalFirstTT = tmpObjects[i].Device[j].Join[k].UNominalFirstTT;
                        cMain.Objects[i].Device[j].Join[k].UNominalSecondTT = tmpObjects[i].Device[j].Join[k].UNominalSecondTT;

                        //Копирование каналов учета присоединения
                        cMain.Objects[i].Device[j].Join[k].Channel = new cMain.CHANNEL[tmpObjects[i].Device[j].Join[k].Channel.Length];
                        for (l = 0; l < cMain.Objects[i].Device[j].Join[k].Channel.Length; l++)
                        {
                            cMain.Objects[i].Device[j].Join[k].Channel[l].ItemAction.DBExist = tmpObjects[i].Device[j].Join[k].Channel[l].ItemAction.DBExist;
                            cMain.Objects[i].Device[j].Join[k].Channel[l].ItemAction.Changed = tmpObjects[i].Device[j].Join[k].Channel[l].ItemAction.Changed;
                            cMain.Objects[i].Device[j].Join[k].Channel[l].ItemAction.Deleted = tmpObjects[i].Device[j].Join[k].Channel[l].ItemAction.Deleted;
                            cMain.Objects[i].Device[j].Join[k].Channel[l].ID = tmpObjects[i].Device[j].Join[k].Channel[l].ID;
                            cMain.Objects[i].Device[j].Join[k].Channel[l].CollectEnable = tmpObjects[i].Device[j].Join[k].Channel[l].CollectEnable;
                            cMain.Objects[i].Device[j].Join[k].Channel[l].EnergyType = tmpObjects[i].Device[j].Join[k].Channel[l].EnergyType;
                            cMain.Objects[i].Device[j].Join[k].Channel[l].MeterSerial = tmpObjects[i].Device[j].Join[k].Channel[l].MeterSerial;
                            cMain.Objects[i].Device[j].Join[k].Channel[l].MeterID = tmpObjects[i].Device[j].Join[k].Channel[l].MeterID;
                            cMain.Objects[i].Device[j].Join[k].Channel[l].ExportNPATSCode = tmpObjects[i].Device[j].Join[k].Channel[l].ExportNPATSCode;
                            cMain.Objects[i].Device[j].Join[k].Channel[l].ImportNPATSCode = tmpObjects[i].Device[j].Join[k].Channel[l].ImportNPATSCode;
                            cMain.Objects[i].Device[j].Join[k].Channel[l].Value63002Code = tmpObjects[i].Device[j].Join[k].Channel[l].Value63002Code;
                            cMain.Objects[i].Device[j].Join[k].Channel[l].ASKPIdentifier = tmpObjects[i].Device[j].Join[k].Channel[l].ASKPIdentifier;
                        }
                        //Копирование линий электропередач присоединения
                        cMain.Objects[i].Device[j].Join[k].ConnLineLosts = new cMain.CONN_LINE_LOSTS[tmpObjects[i].Device[j].Join[k].ConnLineLosts.Length];
                        for (l = 0; l < cMain.Objects[i].Device[j].Join[k].ConnLineLosts.Length; l++)
                        {
                            cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ItemAction.DBExist = tmpObjects[i].Device[j].Join[k].ConnLineLosts[l].ItemAction.DBExist;
                            cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ItemAction.Changed = tmpObjects[i].Device[j].Join[k].ConnLineLosts[l].ItemAction.Changed;
                            cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ItemAction.Deleted = tmpObjects[i].Device[j].Join[k].ConnLineLosts[l].ItemAction.Deleted;
                            cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].ID = tmpObjects[i].Device[j].Join[k].ConnLineLosts[l].ID;
                            cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].LineLength = tmpObjects[i].Device[j].Join[k].ConnLineLosts[l].LineLength;
                            cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].Resistance = tmpObjects[i].Device[j].Join[k].ConnLineLosts[l].Resistance;
                            cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].UNominal = tmpObjects[i].Device[j].Join[k].ConnLineLosts[l].UNominal;
                            cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].CableLost = tmpObjects[i].Device[j].Join[k].ConnLineLosts[l].CableLost;
                            cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].AirLost = tmpObjects[i].Device[j].Join[k].ConnLineLosts[l].AirLost;
                            cMain.Objects[i].Device[j].Join[k].ConnLineLosts[l].CircuitsAmount = tmpObjects[i].Device[j].Join[k].ConnLineLosts[l].CircuitsAmount;
                        }
                        //Копирование групп отчетов присоединения
                        cMain.Objects[i].Device[j].Join[k].ReportGroup = new cMain.REPORT_GROUP[tmpObjects[i].Device[j].Join[k].ReportGroup.Length];
                        for (l = 0; l < cMain.Objects[i].Device[j].Join[k].ReportGroup.Length; l++)
                        {
                            cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ItemAction.DBExist = tmpObjects[i].Device[j].Join[k].ReportGroup[l].ItemAction.DBExist;
                            cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ItemAction.Changed = tmpObjects[i].Device[j].Join[k].ReportGroup[l].ItemAction.Changed;
                            cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ItemAction.Deleted = tmpObjects[i].Device[j].Join[k].ReportGroup[l].ItemAction.Deleted;
                            cMain.Objects[i].Device[j].Join[k].ReportGroup[l].ID = tmpObjects[i].Device[j].Join[k].ReportGroup[l].ID;
                            cMain.Objects[i].Device[j].Join[k].ReportGroup[l].RGType = tmpObjects[i].Device[j].Join[k].ReportGroup[l].RGType;
                        }
                    }
                }
            }
            tmpObjects = new cMain.OBJECT[0];
        }
        //Удаление из массива территориальных объединений структур отмеченных на удаление
        private static void RefreshDC()
        {
            Int32 i;
            cMain.DC_ITEM[] tmpDC = new cMain.DC_ITEM[0];

            for (i = 0; i < cMain.DC.Length; i++)
            {
                if ((cMain.DC[i].ItemAction.DBExist) ||
                    ((!cMain.DC[i].ItemAction.DBExist) && (!cMain.DC[i].ItemAction.Deleted)))
                {
                    Array.Resize(ref tmpDC, tmpDC.Length + 1);
                    tmpDC[tmpDC.Length - 1].ItemAction.DBExist = cMain.DC[i].ItemAction.DBExist;
                    tmpDC[tmpDC.Length - 1].ItemAction.Changed = cMain.DC[i].ItemAction.Changed;
                    tmpDC[tmpDC.Length - 1].ItemAction.Deleted = cMain.DC[i].ItemAction.Deleted;
                    tmpDC[tmpDC.Length - 1].ParentID = cMain.DC[i].ParentID;
                    tmpDC[tmpDC.Length - 1].ID = cMain.DC[i].ID;
                    tmpDC[tmpDC.Length - 1].Caption = cMain.DC[i].Caption;                    
                }
            }
            cMain.DC = new cMain.DC_ITEM[tmpDC.Length];
            for (i = 0; i < cMain.DC.Length; i++)
            {
                cMain.DC[i].ItemAction.DBExist = tmpDC[i].ItemAction.DBExist;
                cMain.DC[i].ItemAction.Changed = tmpDC[i].ItemAction.Changed;
                cMain.DC[i].ItemAction.Deleted = tmpDC[i].ItemAction.Deleted;
                cMain.DC[i].ParentID = tmpDC[i].ParentID;
                cMain.DC[i].ID = tmpDC[i].ID;
                cMain.DC[i].Caption = tmpDC[i].Caption;                
            }
            tmpDC = new cMain.DC_ITEM[0];
        }

        public static string FixIdentifierName(string IDName)
        {
/*
            int StrLen = IDName.Length;
            string Result = IDName;
            for (int i = StrLen - 1; i >= 0; i--)
            {
                if (Result.ToCharArray()[i] == "'".ToCharArray()[0])
                {
                    Result = Result.Insert(i, "'");
                }
            }
            return Result;
*/
            // система Ленин-Сталин
            // Теперь не нужно обрабатывать ковычки!
            // Теперь нужно их удалять!
            // в соответсвии с 0003752: После сбора с СЕ102 данные не отображаются
            // Минин В. 07-02-2013 
            return IDName.Replace("'", "");
        }

        private cDbOracle() { }
    }
}
